Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom LogEventLevel with Serilog

I'm using Serilog and Seq with a .Net project. My main objective is to log some specific events. I would like to have my own log event level (like "Warning", "Verbose", "Information"...). But I don't really know if it's possible or not to have my custom log level for having this:

private static readonly ILogger Logger = Log.ForContext<MyController>();
        .
        .
        .
Logger.MyCustomLogLevel(....);

Is it possible?

like image 803
Régis NIOX Avatar asked Apr 24 '18 13:04

Régis NIOX


People also ask

How to create a Serilog Logger?

Create a Console Application project in Visual Studio. Install Serilog and its dependencies. Create and configure the Serilog global logger. Integrate the logger into the C# Console Application.

Why to use Serilog?

It's designed to work well with others. Serilog is the reference example of a Structured Logging system - one that doesn't just create messages, it easily captures key attributes and data about the context the message happened in.

What is a Serilog sink?

Serilog is a structured logging library for . NET with more features and better performance than the built-in Microsoft logging libraries, but the standard console sink is still slow. Console output is a bytestream managed by the underlying OS.


1 Answers

Although custom levels are not possible, imagining you want to create (logically) and Important level you can achieve close to the same thing with:

static class LoggerExtensions
{
  public static void Important(
    this ILogger logger,
    string messageTemplate,
    params object[] args)
  {
    logger.ForContext("IsImportant", true)
      .Information(messageTemplate, args);
  }
}

Usage:

Logger.Important("Hello, {Name}!", "World");

In Seq:

IsImportant = true

Or:

select count(*) from stream where IsImportant limit 10
like image 60
Nicholas Blumhardt Avatar answered Sep 19 '22 10:09

Nicholas Blumhardt