How to use serilog in ASP. Net core

Time:2021-6-2

One of the functions of logging is to facilitate the tracking and debugging of applications, which is introduced in practical applicationsLog frameworkBut if yourlog fileIf it contains unstructured data, it will be a nightmare to query, so we need to use structured method when recording logs.

Structured logs can be more easily queried and analyzed by defining the data format when writing, including XML, JSON, or any structure you want to convert.

Serilog is a third-party, open-source, structured logging framework. Its high-level encapsulation makes it easier for developers to record logs to console, file and all kinds of files you can think ofstorage system In this article, we will discuss how to use serilog in ASP. Net core.

Install serilog

Use visual studio to create a new ASP. Net core project, and then pull several packages from nuget, as follows:

  • Serilog

This package provides functional support for basic structured logging.

  • Serilog.AspNetCore

This package provides serilog support for aspnetcore.

  • Serilog.Settings.Configuration

This package gets through serilog and configuration, so you can read the configuration directly from Appsettings. JSON.

  • Serilog.Sinks.Console

Console receiver, as the name suggests, is to output the log of serilog to console.

  • Serilog.Sinks.RollingFile

The realization of theScrolling filesWe need your support.

Using serilog sink

Serilog uses the sink feature to send logs to different places, such as text files, databases, and even elastic search. In other words, the sink feature can send logs to where they should go. After all nuget packages are installed, the following code fragment shows how to send logs to console.


        public HomeController(ILogger<HomeController> logger)
        {
            using (var logConfig = new LoggerConfiguration().WriteTo.Console().CreateLogger())
            {
                logConfig.Information("This is a test data.");
            };

            _logger = logger;
        }

How to use serilog in ASP. Net core

It is worth noting that serilog supports multiple log levels, such as: verb, debug, information, warning, error and fatal.

Sometimes it’s a good way to send logs to console for debugging purposes, but after the program is deployed to production, a more common way is to record the logs to a file, so that it’s convenient to view the logs in real time and do a certain degree of log analysis in production. It’s just hereSerilog.Sink.RollingFileThe following code fragment shows how to send logs to files programmatically.


        public HomeController()
        {
            var logger = new LoggerConfiguration().MinimumLevel.Debug().WriteTo
                                                  .RollingFile(@"e:\log.txt", retainedFileCountLimit: 7)
                                                  .CreateLogger();

            for (int i = 0; i < byte.MaxValue; i++)
            {
                logger.Information($"log {i}");
            }
        }

How to use serilog in ASP. Net core

Replacing native logger with serilog

The logger component is built into the asp.net core. In this section, we will see how to replace it with serilogProgram.MainThe following code is used in the method:


    public class Program
    {
        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
             .MinimumLevel.Debug()
             .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
             .Enrich.FromLogContext()
             .WriteTo.Console()
             .CreateLogger();

            try
            {
                Log.Information("Starting web host");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
              .UseSerilog()
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

As you can see from the above code, I used theUseSerilog()Expand the method to start the serilog, so that the replacement of the serilog is completed. Next, you can obtain the logger instance in the controller through dependency injection, as shown in the following code:


        public IActionResult Index()
        {
            logger.LogInformation("hello world");

            return View();
        }

How to use serilog in ASP. Net core

Logging is an integral part of an application, so choose oneflexible + simpleSerilog provides low configuration and easy to use features, so that we can easily send logs to various places.

Translation link: https://www.infoworld.com/art…

More high quality dry goods: see my GitHub: csharptranslate