Using Log4j/Log4net-style short log levels with Serilog

A simple code snippet that allows you to use Log4j/Log4net-style short log levels with Serilog


Log4j (and thus Log4net) typically format their common log levels as so: DEBUG, INFO, WARN, ERROR, FATAL. Note that some of these are 4 characters long and some are 5 characters long. Serilog, on the other hand, will either format the log levels in full (Debug, Information, Warning, Error, Fatal), or have them all set to the same length when using short level names (for example: DBG, INF, WRN, ERR, FTL). There's no out-of-the-box way for Serilog to format short level names with a mix of 4-character and 5-character levels to match how Log4j or Log4net do things.

Luckily, we can define a custom enricher to help do this:

private sealed class CustomLevelEnricher : ILogEventEnricher
{
    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        var level = logEvent.Level switch
        {
            LogEventLevel.Verbose => "VERB",
            LogEventLevel.Debug => "DEBUG",
            LogEventLevel.Information => "INFO",
            LogEventLevel.Warning => "WARN",
            LogEventLevel.Error => "ERROR",
            LogEventLevel.Fatal => "FATAL",
            _ => string.Empty,
        };

        logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("CustomLevel", level));
    }
}

We can then attach this custom enricher to our configuration, and use the CustomLevel property in our output template:

var logger = new LoggerConfiguration()
    .Enrich.With<CustomLevelEnricher>()
    .WriteTo.File(path, outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{CustomLevel}] {Message:lj}{NewLine}{Exception}")
    .CreateLogger();

Hope you find this useful.


Posted by Matthew King on 27 April 2022
Permission is granted to use all code snippets under CC BY-SA 3.0 (just like StackOverflow), or the MIT license - your choice!