Search code examples
.net-coreilogger

Accessing parameters sent to the Custom Logger .NETCore 3.1


I am trying to implement custom ILogger . NetCore 3.1

CustomLogger class implements the ILogger. one of the methods thats need to be implemented is:

 public class AuditLogLogger: ILogger
 {
    public IDisposable BeginScope<TState>(TState state)
    {
        return null;
    }

    public bool IsEnabled(LogLevel logLevel)
    {
        return true;
    }
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
   // How can I access the parameters I sent it from the controller?
}
}

From My controller I triggered the LogInformation Method and passeed a string, and a List of KeyValuePair as such:

List<KeyValuePair<string, string>> udf = new List<KeyValuePair<string, string>>();
udf.Add(new KeyValuePair<string, string>("Test", "Test"));
_logger.LogInformation("This is a test", udf);

My code is able to make it to the Log<TState> but I need to perform some logic based on the parameters passed in. How can I access the parameters passed?


Solution

  • I ended up doing a dirty solution Basically, have my controller send in a json string containing the list and message then have the Log function deserialize it such as

    string message = "this is a test";
    List<KeyValuePair<string, string>> udf = new List<KeyValuePair<string, string();
    udf.Add(new KeyValuePair<string, string>("Test", "Test"));
    JObject obj = new JObject();
    obj["Message"] = message;
    obj["MyList"] = JArray.FromObject(udf);
    

    The Log Message needs to deserialize

    I am sure there is a cleaner solution