In this blog post, we will have a look at the different log levels and how to control them.
appsettings.json
If you just created a new ASP.NET Core project, you will find a file called appsettings.json
in the root of your project. This file contains a section called Logging
, which is used to configure the logging behavior of your application. The default configuration looks like this:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
}
}
}
Here you can control your default log level and the log level of specific namespaces. The default log level is used for all namespaces that are not explicitly configured. In the example above, the default log level is set to Information
and the log level of the Microsoft.AspNetCore
namespace is set to Warning
. So when you use logger.LogWarning
in your code, it will be logged, but when you use logger.LogInformation
it will not be logged.
Custom objects
Let's assume you have a class like this:
namespace MyDomain;
public class MyClass
{
private readonly ILogger<MyClass> _logger;
public MyClass(ILogger<MyClass> logger)
{
_logger = logger;
}
public void Do()
{
_logger.LogDebug("Hey");
}
}
Normally if you call Do
it will not be logged, because the default log level is Information
. But with the following LogLevel
inside the appsettings.json
file, it will be logged:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"MyDomain": "Debug"
}
}
}
The terminal will show:
dbug: MyDomain.MyClass.Do[0]
Hey
So as long as your full qualified class name is part of the configured namespace inside the appsettings.json
file, it will override the default log level. The logger will take the most specific log level. So if you have a class called MyDomain.MyClass
and you configure the log level for MyDomain
and MyDomain.MyClass
, the log level for MyDomain.MyClass
will be used.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"MyDomain": "Debug",
"MyDomain.MyClass": "Warning"
}
}
}
In this case, Do
will not log anything out.
Conclusion
In this blog post, we have seen how to control the log level of your application. You can configure the default log level and the log level of specific namespaces. The logger will take the most specific log level. So if you have a class called MyDomain.MyClass
and you configure the log level for MyDomain
and MyDomain.MyClass
, the log level for MyDomain.MyClass
will be used.