logo MSJO.kr

C#, Logging files with NLog

2020-04-20
MsJ
   

NLog는 풍부한 로그 라우팅 및 관리 기능을 가진 .NET 용 무료 로깅 플랫폼이다. 고품질 로그를 쉽게 생성하고 관리할 수 있다. 원하는 형식을 파일이나 데이터베이스에 같은 대상으로 보낼 수 있다. 다른 진단 로깅 라이브러리로는 Serilog가 있는데 ‘Worker Services in .NET Core 3.0’ 포스팅에서 소개하였고 이번 글에서는 NLog Wiki‘Getting started with .NET Core 2 Console application’ 글을 참고하여 사용법을 간단하게 작성해보았다.

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">
  <targets>
    <target name="file" xsi:type="File"
      layout="[${date:format=HH\:mm\:ss} ${level:uppercase=true:padding=5}] : ${message} ${callsite:className=false:fileName=true:includeSourcePath=false:methodName=false}[${threadid}]"
      fileName="${basedir}/logs/${date:format=yyyyMM}/log_${date:format=yyyyMMdd}.txt" 
      concurrentWrites="true" />
    <target name="n" xsi:type="OutputDebugString" 
      layout="${message}  [${level:uppercase=true}]${callsite:className=false:fileName=true:includeSourcePath=false:methodName=false}[${threadid}]" />  
  </targets>
  <rules>
    <logger name="*" minlevel="trace" writeTo="file" />
    <logger name="*" minlevel="trace" writeTo="n" />
  </rules>
</nlog>
<!-- <targets async="true"> -->
<targets>
  <target name="logfile" xsi:type="AsyncWrapper">
    <target xsi:type="File" fileName="logs/log.txt"
            maxArchiveFiles="10"
            archiveAboveSize="1048576"
            archiveNumbering="Sequence"
            concurrentWrites="true"
            archiveFileName="logs/log.{####}.txt"/>
  </target>
</targets>

<!-- overflowAction -->
<targets>
  <target name="logfile" xsi:type="AsyncWrapper" overflowAction="Grow">
    <target xsi:type="File" fileName="logs/log.txt"
            maxArchiveFiles="10"
            archiveAboveSize="1048576"
            archiveNumbering="Sequence"
            concurrentWrites="true"
            archiveFileName="logs/log.{####}.txt"/>
  </target>
</targets>
Program.cs
/* using NuGet package 
- Microsoft.Extensions.Configuration
- Microsoft.Extensions.Configuration.FileExtensions
- Microsoft.Extensions.DependencyInjection
- NLog
- NLog.Extensions.Logging
*/

using NLog;
using System;
using System.Linq;

namespace ConsoleNLogDemo
{
    internal class Program
    {
        private static readonly Logger logger = LogManager.GetCurrentClassLogger();

        private static string StringRepeatChar(string title, char repeatChar, int countChar)
        {
            return title + string.Concat(Enumerable.Repeat(repeatChar, countChar - title.Length));
        }

        private static void Main()
        {
            try
            {
                logger.Info(StringRepeatChar("Start", '*', 30));
                logger.Log(LogLevel.Debug, "Test...");
                int i = 1;
                int j = 0;
                Console.WriteLine($"{i} / {j} = {i / j}");
                logger.Trace("Trace");
                logger.Debug("Debug");
                logger.Warn("Warn");
                logger.Error("Error");
                logger.Fatal("Fatal");
            }
            catch (Exception ex)
            {
                logger.Fatal(ex.Message);
            }
            finally
            {
                logger.Info(StringRepeatChar("End/Finally", '=', 30));
                //LogManager.Shutdown();
            }
        }
    }
}

/* log_20200420.txt
[11:29:27  INFO] : Start************************* (Program.cs:20)
[11:29:27 DEBUG] : Test... (Program.cs:21)
[11:29:27 FATAL] : Attempted to divide by zero. (Program.cs:24)
[11:29:27  INFO] : End/Finally=================== (Program.cs:17)
*/
Reference

Prεv(Θld)   Nεxt(Nεw)
Content
Search     RSS Feed     BY-NC-ND