Logging errors is an important part of every web application. In here, we will see how to use Nlog to list some information or error in a text file in a .NET Core Web API.
Open Visual Studio and create a new project. Select ASP.NET Core Web Application.
Select API as the template and click the OK button.
Add Nlog.Extensions.Logging NuGet package.
Let's create an interface having each kind of different method to store logs like Debug, Warning, Information, Error etc.
- namespace CoreNLogText
- {
- public interface ILog
- {
- void Information(string message);
- void Warning(string message);
- void Debug(string message);
- void Error(string message);
- }
- }
Implement the above interface in the class and also, get CurrentClassLogger through LogManager of Nlog, i.e., logger.
Call each method through logger and pass the message as a parameter.
- using NLog;
- namespace CoreNLogText
- {
- public class LogNLog : ILog
- {
- private static ILogger logger = LogManager.GetCurrentClassLogger();
-
- public LogNLog()
- {
- }
-
- public void Information(string message)
- {
- logger.Info(message);
- }
-
- public void Warning(string message)
- {
- logger.Warn(message);
- }
-
- public void Debug(string message)
- {
- logger.Debug(message);
- }
-
- public void Error(string message)
- {
- logger.Error(message);
- }
- }
- }
In the startup.cs file, load the configuration for Nlog. For now, give a name like nlog.config and give the root path. In the next step, we will add this file and provide the configuration.
Also, we need to add a singleton service of type Ilog with an implementation type LogNLog.
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using System.IO;
- using NLog;
-
- namespace CoreNLogText
- {
- public class Startup
- {
- public Startup(IConfiguration configuration)
- {
- LogManager.LoadConfiguration(System.String.Concat(Directory.GetCurrentDirectory(), "/nlog.config"));
- Configuration = configuration;
- }
-
- public IConfiguration Configuration { get; }
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc();
-
- services.AddSingleton<ILog, LogNLog>();
- }
-
-
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
-
- app.UseMvc();
- }
- }
- }
In nlog.config, we need to configure two paths for logging. One is InternalLog and another is actual log which we want to write. So, first, provide the internal log file path to the attribute internalLogFile and second, provide the actual path in the target. Add the assembly which we have added through nuGet under extensions. Also, configure the rule where we are mentioning to debug at minimum level and write to log file.
nlog.config
- <?xml version="1.0" encoding="utf-8" ?>
- <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true" internalLogLevel="Trace" internalLogFile="D:\AKKI_DEV\RND\CoreNLogText\CoreNLogText\LOG\InnerLog.txt">
- <extensions>
- <add assembly="NLog.Extended" />
- </extensions>
-
- <targets>
- <target name="logfile" xsi:type="File" fileName="D:/AKKI_DEV/RND/CoreNLogText/CoreNLogText/LOG/${shortdate}_log.txt" layout="${longdate} ${level:uppercase=true} ${message}"/>
- </targets>
-
- <rules>
- <logger name="*" minlevel="Debug" writeTo="logfile" />
- </rules>
- </nlog>
When we create a project with Web API, the values controller is added with default CRUD operation. So, let's use the Get method of that controller and try to add a log in the same. Here, we have called all kinds of log methods from the Controller.
- using Microsoft.AspNetCore.Mvc;
- using System.Collections.Generic;
-
- namespace CoreNLogText.Controllers
- {
- [Route("api/[controller]")]
- public class ValuesController : Controller
- {
- private ILog logger;
- public ValuesController(ILog logger)
- {
- this.logger = logger;
- }
-
-
- [HttpGet]
- public IEnumerable<string> Get()
- {
- logger.Information("Information is logged");
- logger.Warning("Warning is logged");
- logger.Debug("Debug log is logged");
- logger.Error("Error is logged");
-
- return new string[] { "value1", "value2" };
- }
-
-
- [HttpGet("{id}")]
- public string Get(int id)
- {
- return "value";
- }
-
-
- [HttpPost]
- public void Post([FromBody]string value)
- {
- }
-
-
- [HttpPut("{id}")]
- public void Put(int id, [FromBody]string value)
- {
- }
-
-
- [HttpDelete("{id}")]
- public void Delete(int id)
- {
- }
- }
- }
Run the application. The Get method of values controller is called. We can see the result of the API in the browser, as shown below.
Now, go to the configured path in nlog.config and open the text file. You can find the log which was written by the API.
Log
2019-01-18 23:08:04.4985 INFO Information is logged
2019-01-18 23:08:04.5623 WARN Warning is logged
2019-01-18 23:08:04.5623 DEBUG Debug log is logged
2019-01-18 23:08:04.5623 ERROR Error is logged
That's it guys. I hope you enjoyed it. You can download the sample application from here.