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
2. Confirm it works as expected by using any http tool you want. The port number may be different.
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.
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);
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();
}
Test
Now, we can run the solution again to see how it works.
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
};
}
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();
}
3. Run the test again.
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.
Top comments (0)