Joelty
Joelty

Reputation: 2009

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

I'd want to output on console some _logger.Information("text") with colors

e.g if logs message starts with Success then write it with green color

Does anyone have an idea whether this could be achieved without writing your own, new sink?

Upvotes: 1

Views: 4882

Answers (1)

C. Augusto Proiete
C. Augusto Proiete

Reputation: 27828

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

The only way to achieve that today is to write your own custom version of the Console sink. You'd have to implement your own ThemedMessageTemplateRenderer.

Serilog.Sinks.Console allows you to define colors through Themes, 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.

Here is an example of how you would create a custom theme using Serilog.Sinks.Console. In this example, text is displayed in green, and strings in yellow.

screenshot of example custom theme running

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");

Upvotes: 7

Related Questions