Logging in Asp .Net Core 2.0

core5

Logging is very important part of any application as almost all application requires proper logging.

.Net Core 2.0 has some simplified way of implementing logging.

Let us see what are the changes required to enable logging in .Net Core 2.0 application.

First of all, we need to make changes in appsettings.json file as below:

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

Here we have logger provider along with the levels so it allows us to configure logging levels per logging provider.

Previously, the entry in appsettings.json would only be applicable to the console logger but now the entry in the appsettings.json  has logger provider names in it like Debug, EventLog, TraceSource etc.

Do not forget to make these changes as it is required and it may throw the exception if you have missed this. I saw some StackOverflow questions mainly on this where people forgot to add related details in appsettings.json file.

Once it is done, in Main class, we can configure the logging details as shown below:

public static void Main()
{
  var host = new WebHostBuilder()
               .UseKestrel()
               .UseContentRoot(Directory.GetCurrentDirectory())
               .ConfigureAppConfiguration((hostingContext, config) =>
     {
       var env = hostingContext.HostingEnvironment;
       config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
       .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
       .AddJsonFile("hosting.json", optional: false)
       .AddEnvironmentVariables();
       })
       .ConfigureLogging((webhostContext, builder) => {
       builder.AddConfiguration(webhostContext.Configuration.GetSection("Logging"))
       .AddConsole()
       .AddDebug();
})
.UseIISIntegration() .UseStartup() .UseApplicationInsights() .Build(); host.Run(); }

So we can now move the logging configuration part into the WebHostBuilder.

In above code, concentrate on line:

logging.AddConfiguration(hostingContext.Configuration.GetSection(“Logging”));

This method sets up logging to look for configuration in a Logging section, in this case, we can write in appsettings.Development.json file as below:

{
 "Logging": {
   "IncludeScopes": false,
   "Debug": {
   "LogLevel": {
   "Default": "Information"
 }
 },
 "LogLevel": {
   "Default": "Debug"
 }
 }
}

Thus it overrides appsettings.json file.

After this, you can directly inject logger service into the controller as shown below:

private readonly IRepository _repository;
private readonly ILogger _logger;

public MyController(IRepository repository,
ILogger logger)
{
    _repository = repository;
    _logger = logger;
}

Now in your controller class, wherever you want to log for Information then it should be:

_logger.LogInformation(“Information”);

And if we want to log for warning then:

_logger.LogWarning(“WARNING!”);

Same goes for other levels as well.

Exception logging:

The logger method allows us to pass an exception as below:

catch (Exception ex) {
     _logger.LogWarning(ex, "Error");
}

Please note that different providers handle the exception information in different ways.

Some useful StackOverflow QAs:

https://stackoverflow.com/questions/45214468/asp-net-core-2-0-appsettings-development-json-not-working-with-logging-configura

https://stackoverflow.com/questions/45781873/is-net-core-2-0-logging-broken

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s