Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A general, centralized parameter logger method, in C#

Consider this JavaScript code snippet:

Object.prototype.log = function() {
   // here, you have a centralized place to do logging stuff;
   console.log(this);
}

function fullName(firstName, lastName)
{
    // here, using a simple one-line code, you can log all parameters;
    arguments.log();
}

fullName('saeed', 'nemati');

Can we have a similar mechanism for logging all the parameters passed into a method, in C#?

Note: What I've done was to use reflection, but with no success:

public static void LogParameters(this ParameterInfo[] parameters)
{
    StringBuilder builder = new StringBuilder();
    builder.Append("*****************\r\n");
    builder.Append("Parameters\r\n");
    parameters.ToList().ForEach(pi =>
    {
        builder.AppendFormat("{0} => {1}\r\n", pi.Name, pi.DefaultValue);
        // The problem is that, I can't get the value of the parameter here
    });
    builder.Append("*****************");
    Log.Write(builder.ToString());
}

public string GetFullName(string firstName, string lastName)
{
    MethodBase.GetCurrentMethod().GetParameters().LogParameters();
    return firstName + " - " + lastName;
}

GetFullName("saeed", "neamati");
like image 350
Saeed Neamati Avatar asked Jan 18 '23 22:01

Saeed Neamati


1 Answers

No, you can't obtain parameter values using reflection. You'd have to pass them into the logging method explicitly.

You may be able to do this using the debugger API, but you probably don't want to. I would just do it explicitly if I were you - and in fact, that's likely to end up with more useful logging, as you can log only what's important, and give some context in a message as well.

like image 177
Jon Skeet Avatar answered Jan 29 '23 06:01

Jon Skeet