Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I modify Serilog Log Levels to match up with Log4Net?

Tags:

.net

serilog

So I am in the process of swapping logging frameworks from Log4Net to Serilog where we log out to a text file.

I want the format of the text file to be exactly the same as I had previously, so users have a seamless migration.

So with the Serilog File Sink, I am able to modify the outputTemplate to suit my needs, however I am unable to get Serilogs log level to match exactly the same as in Log4Net.

I wish to have:

  • ERROR
  • INFO
  • WARN
  • DEBUG
  • etc...

By reading the documentation for outputTemplates https://github.com/serilog/serilog/wiki/Configuration-Basics#output-templates

For more compact level names, use a format such as {Level:u3} or {Level:w3} for three-character upper- or lowercase level names, respectively.

So I tried the following to try and get 5 letter uppercase {Level:u5} and got back:

  • Infor
  • Error
  • Warni
  • Debug
  • etc..

Is anyone able to give me a pointer on this please?

like image 830
Warren Buckley Avatar asked Jan 28 '23 16:01

Warren Buckley


1 Answers

After digging through the source code of Serilog, I found where the shorthand formatting for u3, w3 etc was happening and submitted a PR so that 5 character length log levels would be output as I needed.

After a polite response from Serilog maintainers, they gave me a much simpler solution of implementing my own ILogEventEnricher to add a new property to the log such as {Log4NetLevel} where the Enricher code can map Serilog Levels to be output in the exact format that Log4Net would use.

Then I can update my outputTemplate to use my new property {Log4NetLevel} as opposed to {Level:u5}

Here is a basic example

/// <summary>
/// This is used to create a new property in Logs called 'Log4NetLevel'
/// So that we can map Serilog levels to Log4Net levels - so log files stay consistent
/// </summary>
public class Log4NetLevelMapperEnricher : ILogEventEnricher
{
    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        var log4NetLevel = string.Empty;

        switch (logEvent.Level)
        {
            case LogEventLevel.Debug:
                log4NetLevel = "DEBUG";
                break;

            case LogEventLevel.Error:
                log4NetLevel = "ERROR";
                break;

            case LogEventLevel.Fatal:
                log4NetLevel = "FATAL";
                break;

            case LogEventLevel.Information:
                log4NetLevel = "INFO";
                break;

            case LogEventLevel.Verbose:
                log4NetLevel = "ALL";
                break;

            case LogEventLevel.Warning:
                log4NetLevel = "WARN";
                break;
        }

        logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("Log4NetLevel", log4NetLevel));
    }
}

Then I simply need to update my Serilog configuration to use my enricher, a much cleaner solution. Thanks Serilog team!

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .Enrich.With<Log4NetLevelMapperEnricher>()
    .WriteTo.File(
        $@"{AppDomain.CurrentDomain.BaseDirectory}\App_Data\Logs\UmbracoTraceLog.{Environment.MachineName}.txt",
        rollingInterval: RollingInterval.Day,
        restrictedToMinimumLevel: LogEventLevel.Debug,
        retainedFileCountLimit: null,
        outputTemplate:
        "{Timestamp:yyyy-MM-dd HH:mm:ss,fff} [P{ProcessId}/D{AppDomainId}/T{ThreadId}] {Log4NetLevel}  {Message:lj}{NewLine}{Exception}")
    .CreateLogger();
like image 50
Warren Buckley Avatar answered Jan 30 '23 07:01

Warren Buckley