Custom LogEventLevel with Serilog
Asked Answered
E

3

9

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?

Eponymous answered 24/4, 2018 at 13:36 Comment(0)
U
12

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
Urbanus answered 25/4, 2018 at 21:54 Comment(1)
That's what I finally did :). ThanksFoetid
T
3

I had to deal with the same problem of logging with a custom log level. Whilst the original question is a bit old, I'm posting here, because none of the answers appear to be accurate.

It is possible to log with a custom log level, though it's a little hacky.

internal static class DebugLogger
{
    private const LogEventLevel LogLevelDebugOnly = (LogEventLevel)0xFF;

    public static void Log(string message)
        => Serilog.Log.Logger.Write(LogLevelDebugOnly, message);

    public static void Log(Exception ex)
        => Serilog.Log.Logger.Write(LogLevelDebugOnly, $"{ex}");
}

Invoke it:

DebugLogger.Log(new DivideByZeroException("BOOM!"));

The result:

2022-06-15 17:21:54.911 +10:00 [255] System.DivideByZeroException: BOOM!
Truscott answered 15/6, 2022 at 7:33 Comment(2)
What is the "0xFF" for?Foetid
A custom log levelTruscott
S
2

Serilog does not support custom log levels.

Stratagem answered 24/4, 2018 at 14:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.