Serilog - 如何使用颜色执行 logger.Information("string")?

Serilog - How to perform logger.Information("string") with Colors?

我想在控制台上输出一些 _logger.Information("text") 颜色

例如,如果日志消息以 Success 开头,则用绿色

书写

有谁知道是否可以在不编写自己的新接收器的情况下实现这一点?

if logs message starts with Success then write it with green color

今天实现这一目标的唯一方法是 编写您自己的自定义版本 Console sink. You'd have to implement your own ThemedMessageTemplateRenderer

Serilog.Sinks.Console , but you can only define colors for a set of known kinds of information such as string or boolean values from properties, or general text, for example. You can see the full list of supported ConsoleThemeStyles in the source code.

这是一个示例,说明如何使用 Serilog.Sinks.Console 创建自定义主题。在此示例中,文本显示为绿色,字符串显示为黄色。

var customThemeStyles =
    new Dictionary<ConsoleThemeStyle, SystemConsoleThemeStyle>
    {
        {
            ConsoleThemeStyle.Text, new SystemConsoleThemeStyle
            {
                Foreground = ConsoleColor.Green,
            }
        },
        {
            ConsoleThemeStyle.String, new SystemConsoleThemeStyle
            {
                Foreground = ConsoleColor.Yellow,
            }
        },
    };

var customTheme = new SystemConsoleTheme(customThemeStyles);

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console(theme: customTheme)
    .CreateLogger();

Log.Information("Good morning {UserName}!!!", "Augusto");