ASP. NET Core Extension Library Log Function Explanation

  • 2021-11-29 23:29:19
  • OfStack

Directory 1. Introduction 2. Use 3. Configuration 4. Configure the log level 5. Dynamic modifications at the log level 6. Local file log configuration 7. Containerization support 8. Test support 9. Disable Serilog

Beginning with a brief introduction to the features of the Xfrogcn. AspNetCore. Extensions extension library in the previous article, I will step through the core features in the extension library.
Log, as a general domain basic function of non-business, has many technical implementations. These third-party libraries avoid us spending time to implement repeatedly. However, many log libraries are complex in configuration, difficult to use and difficult to start with, and some libraries may not be well combined with ASP. NET Core.
If we don't have a detailed understanding of the log library used, the log library can also cause serious problems. In my development career, I have encountered many production accidents caused by the log library.
The Extended Library Log module is dedicated to encapsulating log-related best practices, simplifying the use of log libraries, and truly freeing us from non-business code.

1. Introduction

ASP. NET Core extended library log function is a step forward to Serilog encapsulation, the reason for choosing Serilog, from our practice in the development project, our log library has experienced our own development, choose to use NLog, and finally freeze on the use of Serilog library.
The Serilog log library is also not very easy to use, and may lack some necessary functionality, which is why we need to take a step forward in encapsulation.
The logging feature provides Console and File logging targets by default, both of which support text and Json formats, respectively.
We also added the classification of logs, dynamic modification of log recording level, regular cleaning of local file logs, storage of local log files by directory, support for EFK log architecture under containerization, and support functions of logs in testing.

STEP 2 Use

The log library is enabled with the extension library 1. The simplest case is to enable the extension library. The default configuration will open the file log target, and the log will be stored in the Logs directory under the application, with the date as the folder and the log name as the file name.
There are two ways to open the extension library, either through the UseExtensions method on IHostBuilder or through the AddExtensions method of IServiceCollection in the Startup startup class ConfigureServices method.


//  Pass IHostBuilder Above UseExtensions Method 
  // Program.cs .NET 5.0 
  public class Program
  {
    public static void Main(string[] args)
    {
      CreateHostBuilder(args).Build().Run();
    }

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

Or:


//  In Startup Class 
  public class Startup
  {

    public void ConfigureServices(IServiceCollection services)
    {
      services.AddExtensions(Configuration);
    }
  }

3. Configuration

Logs can be configured by code or by configuration file.
In code form, pass in the configuration object delegate in UseExtensions method or AddExtensions:


public static IHostBuilder CreateHostBuilder(string[] args) =>
      Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
          webBuilder.UseExtensions(args, config=>
          {
            config.AppLogLevel = Serilog.Events.LogEventLevel.Verbose;
            config.SystemLogLevel = Serilog.Events.LogEventLevel.Verbose;
          });
          webBuilder.UseStartup<Startup>();
        });

If you use the configuration file mode, simply set the relevant configuration fields in the configuration source (such as appsettings. json):


{
 "AppLogLevel": "Verbose",
 "AllowedHosts": "*"
}

If both are adopted, the code mode will override the configuration file mode.
In addition, if you need more detailed control over Serilog configuration, you can pass in Serilog log configuration delegate directly in UseExtensions method or AddExtensions. The setting of this delegate will override the above automatic configuration.

4. Configure the log level

In order to simplify the configuration, in the extension library, we divide the logs into system logs, application logs and EFCore logs according to their names, which are controlled by AppLogLevel, SystemLogLevel and EFCoreCommandLevel attributes in the configuration respectively. Log-level configuration supports dynamic modification at runtime without restarting the application.

日志分类
对应日志名
对应配置字段
默认级别
系统日志
Microsoft.* 以及 System.*
SystemLogLevel
Warning
EFCore日志
Microsoft.EntityFrameworkCore.Database.Command
EFCoreCommandLevel
Information
应用日志
除开系统日志及EFCore日志之外的日志
AppLogLevel
Information

5. Dynamic modifications at the log level

If you configure the log level by configuring the source, the log level will be automatically modified when the configuration source is updated (1 through the Reload method of the configuration object).
If you need to use code, you can configure it through the global WebApiConfig instance:


  //  Dynamically Modify Log Levels 
  var apiConfig = host.Services.GetRequiredService<WebApiConfig>();
  apiConfig.AppLogLevel = Serilog.Events.LogEventLevel.Error;

6. Local file log configuration

For the local log configuration, including log file path template, log file timing cleaning, log automatic compression and so on.
The local file log path is configured with the LogPathTemplate setting, which defaults to LogPathTemplates. DayFolderAndLoggerNameFile, indicating daily as the subdirectory and log name as the log file name. Other path templates are also built into LogPathTemplates:

路径模板名
说明
DayFolderAndLoggerNameFile
以每天日期为目录,日志名称为文件名
DayFile
以每天日期为日志名称
LoggerNameAndDayFile
以[日志名称_每天日志]为日志文件名称
LevelFile
以日志级别缩写为日志文件名称
DayFolderAndLevelFile
以每天日期为目录,日志级别缩写为日志名称

Since LogPathTemplate is configured for strings, you can also configure other path templates.
With regard to regular log cleaning, you can specify the number of days to keep the log through MaxLogDays configuration. If it is set to 0, it means no cleaning, which is the default configuration.
The automatic compression strategy of log files can be set through MaxLogFileSize and RetainedFileCount configuration. The default setting of MaxLogFileSize is 100mb. After exceeding this size, the log will be written to a new file. RetainedFileCount is the number of rotatable log files, with a default of 31. After exceeding this number, the log will be automatically compressed.

7. Containerization support

In a containerized environment, Log 1 will generally adopt the architecture of EFK. In k8s, we recommend fluent-bit for F instead of filebeat. Under this framework, we only need to output the log to the console, and the container locates the console output to the Docker host, and then scans the log file through fluent-bit, parses it and sends it to ES.
In this mode, you need to set ConsoleJsonLog to true to turn on the console log target in JSON format. At the same time, because the number of words in a single line of the console is limited, the log may be intercepted, so it may be necessary to set the length limit of a single log through MaxLogLength, which defaults to 8kb, which is suitable for most scenarios. Logs that exceed the length are not ignored, but are split into multiple logs to ensure the integrity of the logs.


//  To support containerization EFK Log mode, 1 You just need to set ConsoleJsonLog For true You can 
  public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
      .ConfigureWebHostDefaults(webBuilder =>
      {
        webBuilder.UseExtensions(args, config=>
        {
          config.ConsoleJsonLog = true;
        });
        webBuilder.UseStartup<Startup>();
      });

8. Test support

Sometimes we may need to check the output of the log in a unit test, and we can use the extension method of the extension library on ILoggingBuilder to add the test log target. You can then get a list of logged log contents via the GetTestLogContent method on IServiceProvider.


IServiceCollection services = new ServiceCollection()
    .AddExtensions()
    .AddLogging(logBuilder =>
    {
      //  Add a test logger 
      logBuilder.AddTestLogger();
    });
    
  IServiceProvider provider = services.BuildServiceProvider();
  //  Getting Log Contents 
  var logContent = provider.GetTestLogContent();

9. Disable Serilog

What if you feel that none of the above features are appropriate for your scenario, but you need to use other features of the extension library? Very simple, you only need to set EnableSerilog to false to completely disable the above logging function.

For detailed log configuration, please refer to [Documentation]
Xfrogcn. AspNetCore. Extensions Address: [GitHub] [Gitee]

The above is the ASP. NET Core extension of the use of the log function details, more about the ASP. NET Core extension of the log function of information please pay attention to other related articles on this site!


Related articles: