Explore ASP.Net Core 3.0 Series Six: ASP.NET Core 3.0 new features start structured log information

Introduction: In this article, I will talk about small changes in 3.0 ASP.NET Core - recorded messages when you start to make small changes. Now, ASP.NET Core will no longer record messages directly to the console, but the proper use of logging infrastructure to generate structured log.

 

A, ASP.NET Core 2.x annoying unstructured log in

When ASP.NET Core 2.x when you start the application, by default, ASP.NET Core will be some output about your application information to the console, such as the current environment, as well as content root path is listening Kestrel the URL. :

 

 These messages are written by WebHostBuilder, the purpose is to provide you with a convenient overview of the application, but it is written directly to the console.

 

This has two major drawbacks:

  •  The only useful information written to the console, it will not write any other logging infrastructure.
  • Write messages to the console is unstructured, their format will be different from any other log written to the console. They did not even log level or source.

The last point is particularly annoying, because usually structured logs to the standard output (console) when running in Docker, then let another process reads the log and sends it to a central location (for example, using fluentd), which is common .

 

Fortunately, in ASP.NET Core 2.1, there is a method you can use environment variables to disable these messages, as my last article exhibited. The only drawback is that the message is completely disabled, and therefore will not record any convenient information, please refer to the detailed article here:

https://andrewlock.net/suppressing-the-startup-and-shutdown-messages-in-asp-net-core/

 

Fortunately, small changes in ASP.NET Core 3.0 provides us with the best of both worlds!

 

Second, the correct logging in ASP.NET Core 3.0 in

If you start using dotnet run ASP.NET Core 3.0 application, you will notice written nuances console log messages:

 

 Now, using a structured start logging messages! But not as simple as using the Console Logger alternative. In ASP.NET Core 2.x, the WebHost responsible for recording these messages. In ASP.NET Core 3.0, these messages by the ConsoleLifetime record, ConsoleLifetime is a generic host registered default IHostLifetime.

I described the role IhostLifetime (especially ConsoleLifetime) in the previous article, but All in all, the class listens for console Ctrl + C keys, and start the shutdown process.

ConsoleLifetime also register a callback during its WaitForStartAsync () method, these callbacks called when the trigger event and the trigger ApplicationLifetime.ApplicationStopping ApplicationLifetime.ApplicationStarted event:

public Task WaitForStartAsync(CancellationToken cancellationToken)
{
    if (!Options.SuppressStatusMessages)
    {
        // Register the callbacks for ApplicationStarted
        _applicationStartedRegistration = ApplicationLifetime.ApplicationStarted.Register(state =>
        {
            ((ConsoleLifetime)state).OnApplicationStarted();
        },
        this);

        // Register the callbacks for ApplicationStopping
        _applicationStoppingRegistration = ApplicationLifetime.ApplicationStopping.Register(state =>
        {
            ((ConsoleLifetime)state).OnApplicationStopping();
        },
        this);
    }

    // ...

    return Task.CompletedTask;
}

OnApplicationStarted () and OnApplicationStopping () operation callbacks simply logging infrastructure write process (as shown below):

private void OnApplicationStarted()
{
    Logger.LogInformation("Application started. Press Ctrl+C to shut down.");
    Logger.LogInformation("Hosting environment: {envName}", Environment.EnvironmentName);
    Logger.LogInformation("Content root path: {contentRoot}", Environment.ContentRootPath);
}

private void OnApplicationStopping()
{
    Logger.LogInformation("Application is shutting down...");
}

Although the exact message is slightly different, but the System Lifetime and Windows ServiceLifetime implementation uses the same method to write the log file through the standard logging infrastructure.

 

Third, the initiation message suppression using ConsoleLifetime

A surprising change start message ConsoleLifetime created cause is that you will no longer be the way I described in an article on the hidden messages. Set ASPNETCORE_SUPPRESSSTATUSMESSAGES apparently did not have any effect - whether the environment variable, the message will continue to record!

As I have already pointed out, the use of Microsoft.Extensions.Logging infrastructure properly recorded messages, so this is now not a big problem. However, if for some reason these messages offends you, and you really want to get rid of them, you can configure ConsoleLifetimeOptions in Startup.cs in:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // ... other configuration
        services.Configure<ConsoleLifetimeOptions>(opts => opts.SuppressStatusMessages = true);
    }
}

 

 

 Now show only the structure of the log information.

If desired, you can even set SuppressStatusMessages field based on the presence ASPNETCORE_SUPPRESSSTATUSMESSAGES environment variables:

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration) => Configuration = configuration;

    public void ConfigureServices(IServiceCollection services)
    {
        // ... other configuration
        services.Configure<ConsoleLifetimeOptions>(opts 
                => opts.SuppressStatusMessages = Configuration["SuppressStatusMessages"] != null);
    }
}

If you do choose not to display a message, please note, Kestrel will record that it is listening URL; otherwise, you will retain its records. There is no way to suppress these:

info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://0.0.0.0:5000
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://0.0.0.0:5001

IV Summary

In this article, I showed how unstructured log record of the log structure in 3.0, to avoid annoying when ASP.NET Core 2.x application startup. This ensures that all configured to write the log recorder, and having a standard format when writing to the console. I described the role IhostLifetime in the log message and explains how to configure ConsoleLifetimeOptions to suppress the status messages as needed.

 

Well, this series of articles on this end, I will be back again to add six articles, the series is completely over, the rest of the project is to continue to engage spike (ASP.Net Core) of CI / CD, for years You can get it.

 

Translation: Andrew Lock    https://andrewlock.net/new-in-aspnetcore-3-structured-logging-for-startup-messages/

 

Author: Guo Zheng

Source: http: //www.cnblogs.com/runningsmallguo/

This article belongs to the author and blog Park total, welcome to reprint, but without the author's consent declared by this section must be retained, and given the original article page link in the apparent position.

Guess you like

Origin www.cnblogs.com/runningsmallguo/p/11618312.html