C# : Add Custom Logger to .NET 6 Web API
Tags: dotnet, webapi, logging
Published: 2022-01-05 05:44:31

Even thought .NET 6 Web API template looks different from previous versions, it still works in the same way. In this article, I will explain how to:

- Use Dependency Injection with .NET 6 Web API template
- Use Custom Logger

# Create new Web API project

1\. First thing first. Let's create new Web API project.

```shell
dotnet new webapi -n loggerwebapi
cd loggerwebapi
dotnet run
```

2\. Confirm it works as expected by using any http tool you want. The port number may be different.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7kwgoxmylftooipap23c.png)
 
# Add Custom Logger

[Implement a custom logging provider in .NET](https://docs.microsoft.com/en-us/dotnet/core/extensions/custom-logging-provider) has detail information, so simply use this as my custom logger.

I simply added three classes from the article and put it into Logger folder.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z88mapb5y9uz7r6ye75a.png)

# DI 

The last step is to add the custom logger via Depedencies Injection. We can do it via ``Program.cs``.

1\. Open Program.cs and add following line under ``// Add services to the container. `` section.

```csharp
builder.Services.TryAddEnumerable(
    ServiceDescriptor.Singleton<ILoggerProvider, ColorConsoleLoggerProvider>());
LoggerProviderOptions.RegisterProviderOptions
    <ColorConsoleLoggerConfiguration, ColorConsoleLoggerProvider>(builder.Services);
```

2\. Add logging code to ``WeatherForecastController.cs``. I added LogInformation to Get method.

```csharp
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
    _logger.LogInformation("test");
    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    })
    .ToArray();
}
```

# Test

Now, we can run the solution again to see how it works.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bc69d26xhg9ebychlzxt.png)
 
# Modify Custom Logger

1\. I modified ``ColorConsoleLoggerConfiguration.cs`` as follows.

```csharp
using Microsoft.Extensions.Logging;

public class ColorConsoleLoggerConfiguration
{
    public int EventId { get; set; }

    public Dictionary<LogLevel, ConsoleColor> LogLevels { get; set; } = new()
    {
        [LogLevel.Information] = ConsoleColor.Cyan,
        [LogLevel.Error] = ConsoleColor.DarkRed,
        [LogLevel.Warning] = ConsoleColor.Blue
    };
}
```

2\. Then I added several more logging code to Get method.

```csharp
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
    _logger.LogError("error");
    _logger.LogWarning("warning");
    _logger.LogInformation("info");

    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = Random.Shared.Next(-20, 55),
        Summary = Summaries[Random.Shared.Next(Summaries.Length)]
    })
    .ToArray();
}
```

3\. Run the test again.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/izi41wfcghjz9iiixdqy.png)


# Summary

Even though .NET 6 templates looks different due to some simplification with new features, it still works in a same way as previous versions.

It's okay to use old style if we want, but I think it's good to know how to code it in the latest way as well.