ASP.NET 5: How to configure the path of logs in Microsoft.Extensions.Logging

18.4k Views Asked by At

I'm working on an MVC6 web app and I'm new to ASP.NET 5. I can see that the Logging (Microsoft.Extensions.Logging) is used at many places (eg: AccountController.cs) in ASP.NET 5 default web application template, but I couldn't figure out where to configure the path of the created log file. Below settings are found in appsettings.json file.

"Logging": {
"IncludeScopes": false,
"LogLevel": {
  "Default": "Verbose",
  "System": "Information",
  "Microsoft": "Information"
}  }

Is it enough to add a parameter in this section? If yes, what is the parameter name? If no, how to do it?

Previously I used Log4Net and configurations were done inside logger.config file.

3

There are 3 best solutions below

1
On BEST ANSWER

ILogger is just an abstraction, you have to implement a concrete logger (log4net, serilog, ...) to log in a file.

public Startup(IHostingEnvironment env)
{
    // Some other code 

    Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug().WriteTo.File("YOUR FILE PATH HERE")
            .CreateLogger();

}

In configure's method (using serilog here) :

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddSerilog();

    // Some other code
}

Official documentation

5
On

There is no built-in file logger in ASP.NET Core. Logging Github repository

But there is a port to use log4net on ASP.NET Core. Link to sources and the blog post

0
On

Use Serilog, Add file logging to ASP.NET Core apps with one line of code.

Install Serilog.Extensions.Logging.File

Host.CreateDefaultBuilder(args)
            .ConfigureLogging((hostingContext, builder) =>
            {
                builder.AddFile("Logs/myapp-{Date}.txt");
            })

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