Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

.net 6 how to introduce a third-party log library in developing TodoList applications

2025-04-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how to introduce a third-party log library in the development of TodoList applications in .NET 6. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

1. Demand

During the development of our project, using the log system built in .NET 6 sometimes cannot meet the actual needs. For example, sometimes we need to output logs to third-party platforms. The most typical application is on various cloud platforms. In order to centrally manage logs and query logs, we usually choose the log SDK of the corresponding platform for integration. Using a variety of Sink provided by Serilog, you can write logs to log storage on different cloud platforms or non-cloud platforms. This is what we will study in this article.

two。 target

We will add a logging policy for TodoList to facilitate replacement and expansion. To put it simply, we will actually set up the logging service used in the Infrastructure project dealing with specific third parties, and do dependency injection in the Api project to facilitate the aware use of the logging service without specific logging configuration throughout the application.

3. Principles and ideas

After consulting the official documentation of Serilog and some examples, determine

There are a few things we need to do:

Introduce the Serilog.AspNetCore package (many articles or tutorials ask you to continue to introduce packages like Serilog.Sink.File according to the Sink you need, but in fact, File is already included in the dependencies of the Serilog.AspNetCore package, so there is no need to add it again.)

Second, you need to provide a LoggerConfiguration for the Logger object of Serilog, which can be configured in code or by loading a .json file, depending on your own needs and whether there are any unique requirements for configuration hot updates.

Declare UseSerilog () when the program starts to construct the WebApplicationBuilder object

You can inject the ILogger object where you need to use the log, usually in the constructor, but you can also choose the other two injection methods.

OK, now that we understand the principle, the next step is to think about where we are going to do these things.

In the second article, I mentioned Clean Architecture, which has a principle that if the system needs to integrate or interact with external (third-party) systems, then the specific integration work should be handled in the Infrastructure layer, while the rest of the program only uses external services abstractly. The advantage is that if you need to replace a third-party system in the future, for example, the original log is written to a local file, and then there is a need for centralized processing of the cloud and log, and you need to interface the log service to such as Azure App Service Logging or AWS CloudWatch, then we only need to modify (extend) the logic of log configuration in Infrastructure. Although the log service itself is relatively simple and does not well reflect this advantage, let's follow this principle and put the configuration work into Infrastructure.

4. Realize

4.1 Log configuration implementation

We added a new folder in the TodoList.Infrastructure project, named Log, and created a new file ConfigureLogProvider.cs in it to implement an extension method for WebApplicationBuilder. In order to demonstrate the scalability of the configuration here, I used an extra field in appsettings.json to control the configuration process. The missing package needs to be installed.

Using Microsoft.AspNetCore.Builder;using Microsoft.Extensions.Configuration;using Serilog;namespace TodoList.Infrastructure.Log Public static class ConfigureLogProvider {public static void ConfigureLog (this WebApplicationBuilder builder) {if (builder.Configuration.GetValue ("UseFileToLog")) {/ / configuration outputs to both the console and the file, and specifies the file name and file dump method (such as log-20211219.txt format). The dump file is retained for 15 days. And the log format / / configure Enrich.FromLogContext () to get some key information from the log context, such as user ID or request ID, which is not used in our application for the time being. Serilog.Log.Logger = new LoggerConfiguration () .Enrich.FromLogContext () .WriteTo.console () .WriteTo.File ("logs/log-.txt", outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj} {NewLine} {Exception}" RollingInterval: RollingInterval.Day, retainedFileCountLimit: 15) .CreateLogger () } else {/ / only configure console log Serilog.Log.Logger = new LoggerConfiguration () .Enrich.FromLogContext () .WriteTo.Console () .CreateLogger () } / / use Serilog as the logging framework, note that it is written differently from .NET 5 and previous versions. Builder.Host.UseSerilog ();}} 4.2 main program configuration

In the Main.cs of the TodoList.Api project, use this extension method:

Using TodoList.Infrastructure.Log;var builder = WebApplication.CreateBuilder (args); / / Add services to the container.// configuration log builder.ConfigureLog (); builder.Services.AddControllers (); / /. Omit the following

And add configuration items to the appsettings.Development.json file for testing:

{"Logging": {"LogLevel": {"Default": "Information", "Microsoft.AspNetCore": "Warning"}}, "UseFileToLog": true} 4.3 injection

Um... I added back the examples WeatherForecastController.cs and WeatherForecast.cs that I deleted at the end of the second article. ILogger has been injected into Controller, so let's try it in the interface of the example:

[HttpGet (Name = "GetWeatherForecast")] public IEnumerable Get () {/ / logging _ logger.LogInformation ($"maybe this log is provided by Serilog..."); return Enumerable.Range (1,5) .Select (index = > new WeatherForecast {Date = DateTime.Now.AddDays (index), TemperatureC = Random.Shared.Next (- 20,55), Summary = Summares [Random.Shared.Next (Summaries.Length)]}) .ToArray ();}

All right, that's it. We can verify it.

5. Verification

To run the TodoList.Api project, as in the second article, we use the Hoppscotch test sample interface to observe the output content and format of the console and log files:

Console output

File output

This is the end of the article on "how to introduce a third-party log library in the development of .NET 6 TodoList applications". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report