ASP.NET (especially ASP.NET Core) supports logging via the built-in Microsoft.Extensions.Logging framework.
The logging verbosity is categorized into the following levels:
- 1. Trace Most detailed. Includes all diagnostic information. Useful during development or deep debugging.
- 2. Debug Less detailed than Trace. Used for debugging during development. Not typically enabled in production.
- 3. Information General flow of the application (e.g., startup, shutdown, user actions). Useful for understanding what the app is doing.
- 4. Warning Something unexpected or potentially problematic happened, but the app can continue running.
- 5. Error A failure occurred during the current operation, but the app continues.
- 6. Critical A fatal error or application crash. The application may be unable to continue running.
- 7. None Logging is completely disabled.
1. Using appsettings.json
In the Logging section, which is used to configure the logging behavior of your application. The default configuration is :
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
}
}
}
In the above configuration you can control your default log level and the log level of specific namespaces.
The default log level is applied to all namespaces that are not explicitly configured.
Here 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 code, it will be logged, but when you use logger.LogInformation it will not be logged.
Suppose we have a class like this :
namespace ProductsDomain
public class HomeController
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.LogInformation("Index page loaded.");
_logger.LogWarning("This is a warning.");
_logger.LogError("An error occurred.");
return View();
}
}
Normally if you call the controller method,LogWarning and LogError will not be logged, because the default log level is Information.
But if you change the following LogLevel inside the appsettings.json file, it will be logged:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"ProductsDomain.HomeController": "Warning"
"ProductsDomain.HomeController": "Error"
}
}
}
So if class name along with namespace is part of the configured namespace inside the appsettings.json file, it will override the default log level. The logger will apply the most specific log level
Top comments (0)