SeriLog color themes
Tags: csharp, dotnetcore, architecture, webdev
Published: 2023-02-18 21:46:28

## 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.

- [SeriLog](https://www.nuget.org/packages/Serilog/3.0.0-dev-01862) for console projects for for ASP.NET Core [SeriLog.AspNetCore](https://www.nuget.org/packages/Serilog.AspNetCore/6.1.1-dev-00295).

- [Serilog.Sinks.Console](https://www.nuget.org/packages/Serilog.Sinks.Console/4.1.1-dev-00907)

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

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

In Index page.

```csharp
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);
}
```
Run the project, inspect the output in the console window we get the following.


![Default SeriLog console output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wxubxmk0cgtaonm9hkvw.png)

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

- The following [built-in themes](https://github.com/serilog/serilog-sinks-console) are available

```csharp
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .WriteTo.Console(theme: AnsiConsoleTheme.Grayscale)
    .CreateLogger();
```
Run the project again and we get the following.


![Gray scale color theme log](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8dtn3hn8t9nm3sqlaziv.png)


## 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](https://www.nuget.org/packages/Serilog.Sinks.Console/4.1.1-dev-00907) 
- 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.

```csharp
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);
    }
}
```
Back in an ASP.NET Core project add the following class (which keeps Program.cs or Startup.cs clean).

```csharp
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();
    }
}
```

In Program.cs

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

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

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


![simple color theme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ucevcvpp4bqm5x4vpwy3.png)

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.

- Microsoft [Hosting your own NuGet feeds](https://learn.microsoft.com/en-us/nuget/hosting-packages/overview)
- Code Magazine [Working with NuGet Local Packages](https://www.codemag.com/Article/2109091/Working-with-NuGet-Local-Packages) by Karen Payne

## 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](https://www.nuget.org/packages/SeriLogThemesLibrary/1.0.0.1) with full source code. If none of the themes work for a developer, clone the [source code](https://github.com/karenpayneoregon/serilog-console-themes/tree/master/SeriLogThemesLibrary), 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lkoxbuxkwullbo5d0ymn.png)

**Theme2**
![Theme2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y9hsyvkcwy6jha6nx81b.png)

**Theme3**
![Theme3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ifea4j8mcdegthrsya8u.png)

**Theme4**
![Theme4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7s1mq7lphfeprrnuhms3.png)

**Theme5**

![Theme5](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ty0fur72lii1xn92qedc.png)

## SeriLog themes internals

For seasoned/advance developers check out [Serilog.Sinks.SystemConsole.Themes.SystemConsoleThemes](https://github.com/serilog/serilog-sinks-console/blob/dev/src/Serilog.Sinks.Console/Sinks/SystemConsole/Themes/SystemConsoleThemes.cs)

## Source code

Clone the following [GitHub repository](https://github.com/karenpayneoregon/serilog-console-themes) 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](https://www.nuget.org/packages/SeriLogThemesLibrary/1.0.0.1) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2db41o68itl3nkws22jq.png)