简体   繁体   中英

How to format file log output with asp.net core and Serilog

I am testing some basic file logging with Asp.Net Core and I using Serilog as it's quick to setup.

The issue I having is when I log a message from the HomeController using the built in ILogger there is no mention of the controller in the file output. For example.. the logger is in the controller is like this and being injected the usual way in the constructor..

private readonly ILogger<HomeController> _logger;

I am am logging something as a test like this

_logger.LogError("Test error log");         

This appears in the file like this.. with no mention of HomeController.

2019-11-28T11:36:52.7735997+00:00 8000000c-0003-fe00-b63f-84710c7967bb [INF] test info log (72772865)

Also where/how do I format this date so it isn't so long? Its not clear from the docs if its done in the json, or startup.cs. And I dont need the 8000000a-0003-fe00-b63f-84710c7967bb request id.

In startup.cs this is set up as follows

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddFile("Logs/HPPartnerPortal-{Date}.txt");           

My config.json specifies the default of

"Logging": {
    "LogLevel": {
        "Default": "Information",
        "Microsoft": "Warning"          
    }

I notice you can add File logging using the configure method in your startup.cs as I did above.. or you can add it in program.cs as specified in the

https://github.com/serilog/serilog-extensions-logging-file

like this

Host.CreateDefaultBuilder(args)
            //we are setting up logging in Startup.cs so this is not needed ? !
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.AddConsole();
                logging.AddDebug();                 
                //logging.AddFile("Logs/myapp-{Date}.txt"); -- AddFile not recognised?!
            })

The problem here is it doesnt recognise AddFile even though I have added Serilog.Extensions.Logging.File This is 1.1.0 which is the latest version in nuget.

According to the documentation , this should set template in your appsettings.json

{
  "Logging": {
    ...
    "OutputTemplate" : "{Timestamp:HH:mm:ss} {RequestId,13} -[{Level:u3}] {Message} ({EventId:x8}){NewLine}{Exception}",
    ...
  }
}

I tried it but it didn't work for me. If anyone finds it working, please comment.

Edit. Found the solution, you must install 2.0.0 version of extension.

您可以安装 nuget 包Serilog.Extensions.Logging或者您可以修改 Project.json 并添加以下行:

"Serilog.Extensions.Logging": "1.0.0"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM