且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以在 serilog 中更改颜色?

更新时间:2023-09-18 23:49:58

是的,使用 Console sink 时改变颜色的方式是通过

可以在配置接收器时指定主题:

 .WriteTo.Console(theme: AnsiConsoleTheme.Code)

在撰写本文时,以下内置主题可用:

  • ConsoleTheme.None - 没有样式
  • SystemConsoleTheme.Literate - 使用所有 Windows 支持的 System.Console 着色模式复制 Serilog.Sinks.Literate 的样式.NET 目标;这是未指定主题时的默认设置
  • SystemConsoleTheme.Grayscale - 仅使用灰色、白色和黑色阴影的主题
  • AnsiConsoleTheme.Literate - ANSI 16 色版本的literate"主题;我们希望在未来更新它以使用 256 色以获得更精致的外观
  • AnsiConsoleTheme.Grayscale - 灰度"的 ANSI 256 色版本主题
  • AnsiConsoleTheme.Code - 一个受 ANSI 256 色 Visual Studio Code 启发的主题

添加新主题很简单;示例可以在 SystemConsoleThemesAnsiConsoleThemes 类.

I have just integrated Serilog in my dot net core project. It is working really well but I use a dark theme and some logs are really dificult to read. As an example:

This is how I init Serilog:

string environment =  Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
        
LoggerConfiguration loggerConfig = new LoggerConfiguration();
            
if (environment == "Production")
    loggerConfig.MinimumLevel.Information();
                
loggerConfig.MinimumLevel.Override("Microsoft.AspNetCore",
    LogEventLevel.Warning) 
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .WriteTo.File("Logs/app.log");

Is there any way I could change colors to make that black logs white for example?

Yes, the way to change colors when using the Console sink is through themes. You can try one of the built-in ones, or create your own.

The Console sink will colorize output by default:

Themes can be specified when configuring the sink:

    .WriteTo.Console(theme: AnsiConsoleTheme.Code)

The following built-in themes are available as of this writing:

  • ConsoleTheme.None - no styling
  • SystemConsoleTheme.Literate - styled to replicate Serilog.Sinks.Literate, using the System.Console coloring modes supported on all Windows/.NET targets; this is the default when no theme is specified
  • SystemConsoleTheme.Grayscale - a theme using only shades of gray, white, and black
  • AnsiConsoleTheme.Literate - an ANSI 16-color version of the "literate" theme; we expect to update this to use 256-colors for a more refined look in future
  • AnsiConsoleTheme.Grayscale - an ANSI 256-color version of the "grayscale" theme
  • AnsiConsoleTheme.Code - an ANSI 256-color Visual Studio Code-inspired theme

Adding a new theme is straightforward; examples can be found in the SystemConsoleThemes and AnsiConsoleThemes classes.