7 Things Worth Knowing About ASP.NET Core Logging
Logging is an important aspect of any professional web application. You often
need to log data, information, errors, system events, and such things. ASP.NET
Core comes with a set of inbuilt logging components that you can use for this
purpose. To that end this article enumerates through seven things that are worth
knowing about ASP.NET Core logging.
Let's begin !
1. NuGet packages involved
The inbuilt logging functionality of ASP.NET Core is bundled in the
Microsoft.Extensions.Logging namespace. When you create a new ASP.NET Core 2
project the relevant NuGet packages are already included in the
Microsoft.AspNetCore.All metapackage.
If they are not added to your project for some reason you should ensure to
add them as shown above.
2. Interfaces
The logging features of ASP.NET Core are built on the foundation of the
following interfaces :
- ILogger
- ILoggingProvider
- ILoggerFactory
The ILogger interface contains methods that write the specified information
to a log storage. The ILoggingProvider creates an ILogger object. The
ILoggingFactory creates an ILogger using a ILoggingProvider.
The LoggerFactory class is a concrete implementation of ILoggingFactory.
3. Inbuilt loggers
ASP.NET Core comes with the following inbuilt ILogger implementations :
- Console
- Debug
- EventSource
- EventLog
- TraceSource
- Azure App Service
The ConsoleLogger writes the log messages to the system console. The
DebugLogger outputs the log information to Visual Studio debug window. The other
logger classes log messages to their respective stores (for example, Windows
event log).
4. Enable logging in a web application
In order to use any of the loggers mentioned earlier, you need to enable
logging your web application. For ASP.NET Core 2 applications the Program.cs
file contains this piece of code :
The CreateDefaultBuilder() call registers Console and Debug loggers for you.
The other loggers can be registered through the Configure() method as shown
below :
public void Configure(IApplicationBuilder app,
ILoggerFactory loggerFactory)
{
loggerFactory.AddEventSourceLogger();
loggerFactory.AddEventLog();
app.UseMvcWithDefaultRoute();
}
As you can see you the code uses AddEventSourceLogger() and AddEventLog()
methods to register event source logger and event log logger with the system.
Your log messages will now be sent using Windows event log and Windows Event
Tracing (ETW) respectively.
5. Injecting ILogger in MVC and Razor Pages
Before you start logging anything from your controllers or razor pages, you
would want to inject an appropriate ILogger object into them. This is how you do
that in an MVC controller :
public class HomeController : Controller
{
private ILogger logger = null;
public HomeController(ILogger<DebugLogger> logger)
{
this.logger = logger;
}
}
As you can see, the above code receives a DebugLogger in the constructor. You
can then use this ILogger implementation to log the messages.
The razor pages use similar approach. The following code shows the
DebugLogger being injected into a page model.
public class IndexModel : PageModel
{
private ILogger logger = null;
public IndexModel(ILogger<DebugLogger> logger)
{
this.logger = logger;
}
}
6. Write information to a log
Once you grab an ILogger object you can log messages as shown below :
public IActionResult Index()
{
logger.LogInformation("This is a log message!");
return View();
}
The code uses LogInformation() to log a message to the output window. The
logger implementations provide methods such as :
- LogTrace()
- LogDebug()
- LogInformation()
- LogWarning()
- LogError()
- LogCritical()
These methods log a message with a certain "log level". You can use various
overloads of these logging methods to log exception details. For example you can
log exceptions details as shown below :
logger.LogInformation(ex,"This is a log message!");
You can also use Log() method and explicitly specify details such as log
level and event ID.
A sample run of the above code produces the following output :
The usage of these log methods in razor pages is identical to MVC
applications.
7. Log levels
Log levels indicate the importance of the message being logger. A log level
is indicated by a number between 0 to 5, each level intended for the purpose
outlined below :
- 0 - Tracing : Tracing purpose messages.
- 1 - Debug : Short term debugging purposes.
- 2 - Information : Track the flow of the application
- 3 - Warning : Abnormal program flow
- 4 - Error : Errors and exceptions that can't be handled by your code.
- 5 - Critical : Serious system failures or errors.
As you might have guessed the logging methods discussed earlier are meant for
the corresponding log levels. For example, LogInformation() method is intended
to log a message with log level of 2. LogError() is intended to log a message
with log level of 3 and so on.
To read more about error logging in ASP.NET Core go
here.
That's it for now! Keep coding !!