Introduction

In this article, you will learn how to archive log files using NLog with ASP.NET Core .

Most of the time, we will store logs in files, and we should archive them so that we can manage them easier. Let's take a look at how to use NLog to archive log files.

Step 1

Create a new ASP.NET Core Web API Application and install NLog.Web.AspNetCore via nuget.
  1. Install-Package NLog.Web.AspNetCore
Step 2

Create a nlog.config file, and enable copy to bin folder.

We just archive the log files via this configuration file.
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. autoReload="true"
  5. throwConfigExceptions="true">
  6. <!-- the targets to write to -->
  7. <targets>
  8. <target xsi:type="File"
  9. name="archive"
  10. archiveEvery="Day"
  11. archiveFileName = "nlogdemo-{########}.log"
  12. archiveNumbering = "Date"
  13. archiveDateFormat = "yyyyMMdd"
  14. maxArchiveFiles = "4"
  15. fileName="nlogdemo.log"
  16. layout="${longdate}|${level:uppercase=true}|${logger}|${message}" />
  17. </targets>
  18. <!-- rules to map from logger name to target -->
  19. <rules>
  20. <!--All logs, including from Microsoft-->
  21. <logger name="*" minlevel="Warn" writeTo="archive" />
  22. </rules>
  23. </nlog>

Just pay attention to the opions that contains archive.

The above configuration means that we hava a main log file named nlogdemo.log which stores today's log.

It will archive logs daily and the file name of the archive log file will be formatted like nlogdemo-20180505.log.

And the max number of archived log files is 4 which means it will keep only the newest 4 files.

Step 3

Update program.cs so that we can enable NLog.
  1. namespace NLogDemo
  2. {
  3. using Microsoft.AspNetCore;
  4. using Microsoft.AspNetCore.Hosting;
  5. using NLog.Web;
  6. public class Program
  7. {
  8. public static void Main(string[] args)
  9. {
  10. BuildWebHost(args).Run();
  11. }
  12. public static IWebHost BuildWebHost(string[] args) =>
  13. WebHost.CreateDefaultBuilder(args)
  14. .UseStartup<Startup>()
  15. .UseNLog()
  16. .Build();
  17. }
  18. }
Step 4

Write some logs in controller.
  1. private readonly ILogger _logger;
  2. public ValuesController(ILoggerFactory loggerFactory)
  3. {
  4. _logger = loggerFactory.CreateLogger<ValuesController>();
  5. }
  6. // GET api/values
  7. [HttpGet]
  8. public IEnumerable<string> Get()
  9. {
  10. _logger.LogDebug("debug");
  11. _logger.LogError("error");
  12. _logger.LogTrace("trace");
  13. _logger.LogInformation("info");
  14. _logger.LogWarning("warn");
  15. _logger.LogCritical("critical");
  16. return new string[] { "value1", "value2" };
  17. }
Now, change the date of computer to see the results.

Source Code
Summary

This article introduced the basic configuration to acrchive log files using NLog.
Hope this can help you.