How to obtain log level through Serilog

1.5k Views Asked by At

Is there a way to obtain a log-specific log event level? For example, if I logged

Log.Information("This is information")

Could print out a value or somehow obtain what level the log was?

1

There are 1 best solutions below

2
On

Probably, what you need is Serilog Formatting Output. That feature enables you to configure the log output as you want. For example, if you want to place the level and also the message in your log, you could do the following (remember to add in the project your Serilog Sinks dependency, Console in this case):

using Serilog;

namespace SerilogExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .WriteTo.Console(outputTemplate:
                    "[{Timestamp:HH:mm:ss}] {Level:}: {Message:lj}{NewLine}{Exception}")
                .CreateLogger();

            Log.Information("This is information");
        }
    }
}

the example above will print in stdout the following:

[00:30:35] Information: This is information

You could also use custom formatters to a specific tool ingestion (ElasticsearchJsonFormatter for example).