DEV Community

Kenichiro Nakamura
Kenichiro Nakamura

Posted on

3 1

C# : Add Custom Logger to .NET 6 Web API

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.



dotnet new webapi -n loggerwebapi
cd loggerwebapi
dotnet run


Enter fullscreen mode Exit fullscreen mode

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

Image description

Add Custom Logger

Implement a custom logging provider in .NET 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

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.



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


Enter fullscreen mode Exit fullscreen mode

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



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


Enter fullscreen mode Exit fullscreen mode

Test

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

Image description

Modify Custom Logger

1. I modified ColorConsoleLoggerConfiguration.cs as follows.



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
    };
}


Enter fullscreen mode Exit fullscreen mode

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



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


Enter fullscreen mode Exit fullscreen mode

3. Run the test again.

Image description

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.

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay