How i can logging messages from asp.net core appli

2020-07-23 06:24发布

I install asp.net core application as linux daemon. By default dotnet write logs into /var/log/message. But I would like application write its log in specific file and store it permanently. How I can do it? Application use Microsoft.Extensions.Logging.

1条回答
贼婆χ
2楼-- · 2020-07-23 07:03

Logs go where you tell them to go, not a specific location. /var/log/message is the location used by the Debug Provider only.

You need to specify which logging providers you want to use in the logging configuration of your project, as shown in the Logging in .NET Core article.

There's no built-in file provider and there's an ongoing discussion about whether there should be one. Logging to files isn't as simple as it sounds at first - how should the messages be formatted? What about rolling files? File names? Perhaps you want errors and verbose messages to be written to different files? Or use different files per subsystem/area/logger/business in your application, eg one log for the sales service, another to log external service calls?

There are a lot of good open source logging libraries, like Serilog and NLog that address these concerns. Some of the most popular ones are listed in .NET Core's documentation. .NET Core's logging can be configured to easily use those libraries.

For example, you can add a Serilog file target with the appropriate package.

To use it, you need to add a reference to the package, eg in your csproj file :

<PackageReference Include="Serilog.Extensions.Logging.File" Version="2.0.0" />

And add it to the logging configuration with a call to AddFile :

WebHost.CreateDefaultBuilder(args)
    .ConfigureLogging((hostingContext, logging) =>
    {
        logging.AddFile("path/to/Logs/myapp-{Date}.txt");
    })
    .UseStartup<Startup>()
    .Build();

The {Date} argument is used to create rolling log files per date.

You can combine multiple loggers,eg you can write to the console with logging.AddConsole() or keep writing to /var/log/message during development with logging.AddDebug();

You can find many logging providers is you search for Extensions.Logging in NuGet.

You could also integrate other libraries like Serilog in your application and use their loggers. For example, you can use the Serilog.Sinks.Fluentd package to target Fluentd

查看更多
登录 后发表回答