Logging in .NET with NLog
Logging is most important part of development , for figuring out the issues we need to add logging in our application especially if issue is occurring at production.
We have multiple options available for logging but two options are most popular , one of them is NLog and other one is Serilog.
NLog is a free logging platform for .NET with rich log routing and management capabilities. It makes it easy to produce and manage high-quality logs for your application regardless of its size or complexity.
Let’s see how can we install NLog and configure it for our ASP .NET Core Application
Installing NLog
Install these three packages from Nuget package to enable NLog in your application.
Appended versions are latest as for now ( When article is being published)
- NLog (Latest 5.1.2)
- NLog.Extensions.Logging (5.2.2)
- NLog.Web.AspNetCore (5.2.2)
Configure NLog with appSettings.json
Add a NLog section in your appsetting with these lines.
These configurations are responsible for logging the details on console and file , as we have mentioned the file path.
If you don’t want to log the details on file you can exclude logfile from target section and second rule.
Update Program.cs
If you want to write your logs into file then add these lines in Program.cs
Now set up NLog Dependency Injection
We can set up DI like this :
Use Logs
In the controller we can use log by injecting ILogger :
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place