Search code examples
c#inheritancemethodsinitializationnlog

How to launch a "log(all parameters)" request at the beginning of all methods


I'm working on C# project, which all use NLog reference for logging purposes.

As a result, everywhere in the project I can add the line log.Debug("...") and some logging will be shown.

One of my colleagues has written a project, applying lots of classes and methods, but the logging is far too little. What I would like, is for every method to launch the following line at the beginning of its execution:

log.Debug(<list of input parameters>);  // all parameters have a ToString() method

In order to achieve that, I'm thinking of some kind of a base method, like this (pseudo-code):

private <whatever_output_type> base_method(...){
  startup : 
    string output = "";
    for each (param) in GetParameters():
      output += ", " + param.ToString();
    log.Debug(<this_method_name>, output);
}

Then I do the following for every existing method:
Replace:

private void Method1 (int i1, int i2, string S1, SomeClass obj1)
{ ... }
public void Method2 ()
{ ... }

By:

private void Method1 (int i1, int i2, string S1, SomeClass obj1) : base_method
{ ... }
public void Method2 () : base_method
{ ... }

In order to get a more readable logging, I would use indentation, based on callstack framecount, as explained in this URL, but let's first start making this work.

For that, I need the following:

  • How can I retrieve the full list of input parameters of a random method?
  • How can I mention that something must be done at the start of a method and how to I inherit one method from a basic function?

Thanks in advance


Solution

  • Maybe combine this:

    public static void InfoParams(this ILoggger logger, params object[] list)
    {
        logger.Info("{@params}", (object)list);
    }
    

    See also: https://github.com/NLog/NLog/wiki/How-to-use-structured-logging

    You could also consider using one of these: