SeriLog color themes

Karen Payne - Feb 18 '23 - - Dev Community

Introduction

Logging can be critical to the success of an application which range from an enterprise application to an application and developer wrote to get paid for.

Without proper logging, imagine attempting to assist a customer or business user were going to their location is impossible and/or using Microsoft Teams or similar application does not provide sufficient information to diagnose the problem.

Another use for logging is while writing code and results are not as expected, using logging can assist in many cases along with using Visual Studio debugger.

By adding logging capabilities to an application which than can be sent to the developer can save time figuring out a problem.

In this article focus will be on using SeriLog for development, in future articles topics will include digging into using SeriLog writing to files and databases along with separating database logging from non-database code.

Console colors

Out of the box to log to the console with SeriLog, add the following NuGet packages.

Next add the following to Program.cs (for ASP.NET Core)



Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .WriteTo.Console()
    .CreateLogger();


Enter fullscreen mode Exit fullscreen mode

In Index page.



public void OnGet()
{
    Log.Verbose(new Exception("Ooops"), "Darn");

    Log.Information("Int: {P1}", 100);
    Log.Information("Date: {P1}", DateTime.Now);
    Log.Information("Bool: {P1}", true);

    Log.Warning("The {P1} is out of range", 222);

    string fileName = "People.json";
    Log.Error(new FileNotFoundException("Does not exist"), 
        "Fail to find {P1}", fileName);

    int? nullValue = null;
    Log.Information("{P1}", nullValue);

    Log.Fatal("{P1} is crashing the app", DateTime.Now);


    Log.Warning("Out of range {@Position}", 
        new { Top = 25, Left = 134 });

    Log.ForContext("CategoryName", "CategoryValue")
        .Information("My Info {P1}", 555);
}


Enter fullscreen mode Exit fullscreen mode

Run the project, inspect the output in the console window we get the following.

Default SeriLog console output

Suppose you have difficulties reading some of the colors? SeriLog has themes, in the following setup gray scale is used.



Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .WriteTo.Console(theme: AnsiConsoleTheme.Grayscale)
    .CreateLogger();


Enter fullscreen mode Exit fullscreen mode

Run the project again and we get the following.

Gray scale color theme log

Creating custom themes

There may be cases were none of the built-in themes work for a developer. If this is the case it’s possible to create your own themes.

This is done by first creating a class project so the custom theme(s) can be use in more than one project.

Spoiler alert: source code provided as a fully working class project and a NuGet package.

  • Add NuGet package Serilog.Sinks.Console
  • Add a class, in this case named SeriLogCustomThemes
  • Figure out the color(s) that need changing.
  • Experiment with colors as shown in a small example as per below.


public class SeriLogCustomThemes
{

    public static SystemConsoleTheme Theme()
    {
        Dictionary<ConsoleThemeStyle, SystemConsoleThemeStyle> customThemeStyles = new()
            {
                {
                    ConsoleThemeStyle.Text, new SystemConsoleThemeStyle
                    {
                        Foreground = ConsoleColor.Green,
                    }
                },
                {
                    ConsoleThemeStyle.String, new SystemConsoleThemeStyle
                    {
                        Foreground = ConsoleColor.Yellow,
                    }
                },
                {
                    ConsoleThemeStyle.Name, new SystemConsoleThemeStyle
                    {
                        Foreground = ConsoleColor.Black,
                        Background = ConsoleColor.Yellow,
                    }
                }

            };

        return new SystemConsoleTheme(customThemeStyles);
    }
}


Enter fullscreen mode Exit fullscreen mode

Back in an ASP.NET Core project add the following class (which keeps Program.cs or Startup.cs clean).



public class SetupLogging
{
    /// <summary>
    /// Configure logging for development environment
    /// </summary>
    public static void Development()
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Verbose()
            .WriteTo.Console(theme: SeriLogCustomThemes.Theme())
            .CreateLogger();
    }
}


Enter fullscreen mode Exit fullscreen mode

In Program.cs



public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // Add services to the container.
        builder.Services.AddRazorPages();
        SetupLogging.Development();


Enter fullscreen mode Exit fullscreen mode

Run the project and we get the following, granted not much has changed but we have new colors.

simple color theme

Continue working out colors until satisfied. Once stratified with colors, create a local NuGet package. Local packages are easy to use, see the following pages listed below for more details.

Pre-built themes

Some developers may want to change color themes as mentioned but don’t necessarily have the skill and or the time, with that said I published my NuGet package with full source code. If none of the themes work for a developer, clone the source code, make changes (at this stage it’s easy), compile and place in a local NuGet package or when needed add a reference to the compiled code in a project.

Preview of included themes

Theme1
Theme1

Theme2
Theme2

Theme3
Theme3

Theme4
Theme4

Theme5

Theme5

SeriLog themes internals

For seasoned/advance developers check out Serilog.Sinks.SystemConsole.Themes.SystemConsoleThemes

Source code

Clone the following GitHub repository which contains source for the class project and two Razor Pages projects to, if desire alter the color themes included or make your own.

NuGet package

SeriLogThemesLibrary for .NET Core 7

What if your projects are in .NET Core 6?

Once you have cloned the respository, open the class project, alter the .NET Framework and repeat for the other projects.

Project properties

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .