I implemented a custom logger provider. My custom logger has this signature:
public void Log<TState>(LogLevel logLevel, EventId eventId,
TState state, Exception exception, Func<TState, Exception, string> formatter)
How is formatter
being passed?
And how can I implement a custom formatter
? Say, if I want it to be formatting everything in JSON
I'm new to Net Core and I don't fully understand how this works.
To use a custom logger named mylog.info in a custom C++ service, do the following: #include <rwsf/core/LogManager> #include <rwsf/core/Logger> Logger logger = rwsf::LogManager::getLogger("mylog.info"); logger.info("My log message"); All messages logged with logger go to the output file defined for mylog.info .
Usage and registration of the custom logger. By convention, registering services for dependency injection happens as part of the startup routine of an application. The registration occurs in the Program class, or could be delegated to a Startup class.
The Func<TState, Exception, string> formatter
function that is being passed to your function is basically just a utility function to convert the state into a single string message. Inside your logger, you are basically just expected to call formatter(state, exception)
to get the formatted message that should be logged.
Usually, you do not really need to care about the function, other than calling it to get the formatted message, so that’s what all loggers usually do. For the purpose of a JSON logger, you could just ignore it completely, or at least also export the formatted message so it’s there as a readable string.
A quick and dirty JSON logger’s Log
method could actually look like this:
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
var jsonLine = JsonConvert.SerializeObject(new {
logLevel,
eventId,
parameters = (state as IEnumerable<KeyValuePair<string, object>>)?.ToDictionary(i => i.Key, i => i.Value),
message = formatter(state, exception),
exception = exception?.GetType().Name
});
// store the JSON log message somewhere
Console.WriteLine(jsonLine);
}
As you can see, it’s not that much magic to generate the JSON object here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With