January 10, 2017 by Anuraj Estimated read time : 3 mins
This post is about using NLog in ASP.NET Core. NLog is a free logging platform for .NET, Xamarin, Silverlight and Windows Phone with rich log routing and management capabilities. NLog makes it easy to produce and manage high-quality logs for your application regardless of its size or complexity.
To use NLog in ASP.NET Core, first you need to add the NLog package in the project.json file. I am using ASP.NET Core 1.1 version, in the project.json you can add NLog package in the dependencies section. You need to use the "NLog.Extensions.Logging": "1.0.0-rtm-alpha5" package. Once you added the package, you can restore the packages to use NLog in your code. Next you need the configuration file, which is required by NLog, it helps to configure NLog logging options.
It is a typical nlog.config file, which need to be placed in the web project root folder, not in the wwwroot. You can find config file in the GitHub repo as well.
Now you need to modify your startup class configure method to enable NLog and add the configuration options.
It is done. Now if you go and check C:\Temp folder, you can see the log file.
If you want to enable logging in controllers, you can either inject the ILogger using ASP.NET Core DI mechanism, or you can use NLog’s LogManager class.
Logging with ASP.NET Core DI.
Logging with NLog’s LogManager class.
If you are using ASP.NET Core DI mechanism, it will create a new log file, but if you are using NLog own mechanism it will log on the same file. Make sure you’re including the NLog.config file in the publishOptions, include section.