Console Logger

In this chapter you may find some interesting information about using the console logging writer. But before continue reading please note, the console logger is split into two different implementations.

The first implementation called Console Logger Standard can be used platform independently. In contrast to that, the second implementation called Console Logger Windows can only be used on Windows platforms. The reason behind, the Console Logger Windows uses the Win32–API directly to be able to support additional Windows features.

Logger Basic Settings

Below can be found a fully qualified example of how to use the console logger settings. You may recognize that the time format, the part split, the quick edit mode as well as the window title have been changed.

Copy
using Plexdata.LogWriter.Abstraction;
using Plexdata.LogWriter.Definitions;
using Plexdata.LogWriter.Extensions;
using Plexdata.LogWriter.Logging.Windows;
using Plexdata.LogWriter.Settings;
using System;

namespace ConsoleLoggerExample
{
    class Program
    {
        static void Main(String[] args)
        {
            IConsoleLoggerSettings settings = new ConsoleLoggerSettings
            {
                LogLevel = LogLevel.Trace,
                ShowTime = true,
                TimeFormat = "G",
                PartSplit = '|',
                QuickEdit = true,
                WindowTitle = "Console Logger Example",
            };

            ILogger logger = new ConsoleLogger(settings);

            logger.Trace("Trace...");
            logger.Debug("Debug...");
            logger.Verbose("Verbose...");
            logger.Message("Message...");
            logger.Warning("Warning...");
            logger.Error("Error...");
            logger.Fatal("Fatal...");
            logger.Critical("Critical...");
        }
    }
}

With the above settings in mind the message output of the console logger would look like as shown as follows.

Logger Color Settings

Changing the console logger’s message coloring can be done by using property Coloring of the console logger settings. How it can be accomplished is shown below.

Copy
static void Main(String[] args)
{
    ...
    settings.Coloring[LogLevel.Verbose] = new Coloring(ConsoleColor.DarkGreen, ConsoleColor.White);
    settings.Coloring[LogLevel.Critical] = new Coloring(ConsoleColor.DarkGray, ConsoleColor.Magenta);

    logger.Trace("Trace...");
    logger.Debug("Debug...");
    logger.Verbose("Verbose...");
    logger.Message("Message...");
    logger.Warning("Warning...");
    logger.Error("Error...");
    logger.Fatal("Fatal...");
    logger.Critical("Critical...");
    ...            
}

After changing the coloring for message types Verbose and Critical as shown above the message output of the console logger would look like as shown below.

Dependency Injection

Dependency injection is always an important issue. Therefore, this section wants to show how to accomplish this task together with the console logger classes.

Dependency Injection in .NET Core

Using dependency injection in a simple .NET Core application might be a bit tricky. Here are the steps to get it running or just click here to download the complete example project.

Step 1

Start with a new .NET Core console application.

Step 2

Install following NuGet packages.

Step 3

Now create a configuration file, such as appsettings.json, and make sure this file has its properties set to Content and to Copy always. Then add content below to the new configuration file.

Copy
{
  "Plexdata": {
    "LogWriter": {
      "Settings": {
        "LogLevel": "Trace",
        "LogTime": "Local",
        "LogType": "Raw",
        "ShowTime": true,
        "PartSplit": "|",
        "WindowTitle": "Hello World" 
      }
    }
  }
}

Step 4

Implement a class that gets injected with its logger instance like shown as follows.

Copy
public class ExampleClassWithLoggerInjection
{
    private readonly IConsoleLogger logger;

    public ExampleClassWithLoggerInjection(IConsoleLogger logger)
    {
        this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public void MethodToCall()
    {
        this.logger.Message("Here I am...");
    }
}

Step 5

In the program’s Main() method implement the required dependency injection part as shown here.

Copy
static void Main(String[] args)
{
    ILoggerSettingsBuilder builder = new LoggerSettingsBuilder();
    builder.SetFilename(Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json"));

    IServiceCollection service = new ServiceCollection();
    service.AddSingleton<ILoggerSettingsSection>(builder.Build());
    service.AddSingleton<IConsoleLoggerSettings, ConsoleLoggerSettings>();
    service.AddSingleton<IConsoleLogger, ConsoleLogger>();
    service.AddTransient(typeof(ExampleClassWithLoggerInjection));

    IServiceProvider provider = service.BuildServiceProvider();

    ExampleClassWithLoggerInjection example = provider.GetService<ExampleClassWithLoggerInjection>();
    example.MethodToCall();
}

Step 6

Finally, run the program. The console output should look like as shown as here.

Dependency Injection in ASP.NET Core

Using dependency injection in an ASP.NET Core application might be a bit easier. Anyway, here are the steps to get it running or just click here to download the complete example project.

Step 1

Start with a new ASP.NET Core console application and choose API as type in the dialog box. After project creation, open project settings, choose Debug tab, select the project name, for example ConsoleLoggerExample2, from Profile drop–list as well as un–tick the check–box Launch browser. Finally, in the toolbar select the project name, for example ConsoleLoggerExample2, instead of IIS Express.

Step 2

Install following NuGet packages.

Step 3

Open configuration file appsettings.json for edit and add content below.

Copy
{ 
  ...
  "Plexdata": {
    "LogWriter": {
      "Settings": {
        "LogLevel": "Trace",
        "LogTime": "Local",
        "LogType": "Raw",
        "ShowTime": true,
        "PartSplit": "|",
        "WindowTitle": "Hello World"
      }
    }
  }
  ...
}

Step 4

Open file Startup.cs for edit and put following lines into method ConfigureServices() as shown below.

Copy
public void ConfigureServices(IServiceCollection services)
{
    ...
    ILoggerSettingsBuilder builder = new LoggerSettingsBuilder();
    builder.SetFilename("appsettings.json");

    services.AddSingleton<ILoggerSettingsSection>(builder.Build());
    services.AddSingleton<IConsoleLogger, ConsoleLogger>();
    services.AddSingleton<IConsoleLoggerSettings, ConsoleLoggerSettings>();
    ...
}

Step 5

As next it would be useful to inject the console logger somewhere, for example in the value controller. For this purpose open file ValuesController.cs and add a constructor as well as field like shown below.

Copy
private readonly IConsoleLogger logger;

public ValuesController(IConsoleLogger logger)
{
    this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
}

After that, move to method Get() and write a logging message as shown in the next code–snippet.

Copy
public ActionResult<IEnumerable<string>> Get()
{
    this.logger.Message("Here I am...");
    return new string[] { "value1", "value2" };
}

Step 6

Finally, build and run the program. Then open a browser and call URL https://localhost:5001/api/values. After that, the console output should look like as shown as here.

Configuration Example

Last but not least, a fully qualified configuration example as JSON can be seen here.

Copy
{
  "Plexdata": {
    "LogWriter": {
      "Settings": {
        "LogLevel": "Trace",
        "LogTime": "Utc",
        "LogType": "Csv",
        "ShowTime": true,
        "PartSplit": "|",
        "TimeFormat": "s",
        "FullName": false,
        "Culture": "en-US",
        "UseColors": true,
        "QuickEdit": true,
        "WindowTitle": "Hello World",
        "BufferSize": {
          "Width": 250,
          "Lines": 500
        },
        "Coloring": {
          "Trace": {
            "Background": "Gray",
            "Foreground": "Black"
          },
          "Debug": {
            "Foreground": "Gray",
            "Background": "Black"
          },
          "Verbose": {
            "Foreground": "White",
            "Background": "Black"
          },
          "Message": {
            "Foreground": "White",
            "Background": "Black"
          },
          "Warning": {
            "Foreground": "Yellow",
            "Background": "Black"
          },
          "Error": {
            "Foreground": "Red",
            "Background": "Black"
          },
          "Fatal": {
            "Foreground": "Gray",
            "Background": "DarkRed"
          },
          "Critical": {
            "Foreground": "Black",
            "Background": "Red"
          }
        }
      }
    }
  }
}