1. 로깅 하는 이유 및 Zlogger쓰는 이유

디버깅/에러 뿐만 아니라 통계 목적에서 로거를 많이 사용한다. JSON형태로 로그를 남겨야 통계가 편한다. 이 중 앞으로 사용할 Zlogger는 일반 내장 logger를 비교하면 다음과 같은 이점이 있다.

Untitled

기존 내장 로거는 다음과 같은 문제를 가진다

  1. 전달되는 Object로 boxing 하는데 비용이 소유된다.
  2. 전달되는 문자열을 새 String으로 할당하거나 캐쉬버에 쓰는데 비용이 발생한다.
  3. String타입의 메세지 등을 UTF8로 엔코딩 하는데 비용이 소요된다.

Zlogger는 다음과 같은 이점을 가진다.

  1. ZString을 이용해서 UTF8로 직접 버퍼에 써서 Boxing 및 엔코딩 비용이 적다.
  2. 비동기적으로 로깅을 수행하여 부하량이 적다

2. Zlogger 적용 및 사용

2.1 서비스 등록(at program.cs)

var builder = WebApplication.CreateBuilder(args);
...
// builder에 서비스 등록
builder.Services.AddLogging(logging =>
{
    // optional(MS.E.Logging):clear default providers.
		//   provider : console, loggerfile, rollingfile
    logging.ClearProviders();
    // optional(MS.E.Logging): default is Info, you can use this or AddFilter to filtering log.
    logging.SetMinimumLevel(LogLevel.Debug);
    // provider1. Add Console Logging.
		//   콘솔 로깅의 방식을 구조화 된 로깅 방식으로 설정한다.
    logging.AddZLoggerConsole(options => { options.EnableStructuredLogging = true; });
    // provider2. Add File Logging.
		//   logging.AddZLoggerFile(String 파일명, Action<ZLoggerOptions> configure)
		//   로깅 파일의 방식을 구조화 된 로깅 방식으로 설정한다.
    logging.AddZLoggerFile("TestLogFile.log", **options => { options.EnableStructuredLogging = true; }**);
    // provider3. Add Rolling File Logging.
		//   Rolling파일의 파일 명 형태를 설정한다.
    logging.AddZLoggerRollingFile((dt, x) => $"logs/{dt.ToLocalTime():yyyy-MM-dd}_{x:000}.log", x => x.ToLocalTime().Date, 1024);
});
...

참고 : 도커에 서버를 돌릴 때는 콘솔 내용들이 자동으로 파일로 로깅 되기 때문에 AddZLoggerConsole()만 설정 해도 된다고 한다.

2.2 로거를 사용할 서비스/컨트롤러에 DI

public class MysqlAccountDb : IAccountDb
{
  private readonly ILogger _logger;
  public MysqlAccountDb(ILogger<MysqlAccountDb> logger)
  {
    _logger = logger;
  }
	...
}

2.3 EnvntId 정의

public class LogEventId
{
	// Controller 이벤트 id
	public static readonly EventId Regist = new EventId(1, "Regist");
	public static readonly EventId Login = new EventId(2, "Login");
	...
	// DB 이벤트 id 
	public static readonly EventId AccountDb = new Event(101, "AccountDb");
	...
}

2.4 로거 사용

2.4.1 주로 사용할 로깅 메서드 분석

// 일반적인 로깅(레벨에 따라 Information대신 Error나 Debug등으로 교체)
public static void ZLogInformationWithPayload<TPayload>(this ILogger logger, EventId eventId, TPayload payload, string message)
// 예외 정보를 포함한 로깅
public static void ZLogInformationWithPayload<TPayload>(this ILogger logger, EventId eventId, Exception? exception, TPayload payload, string message)

2.4.2 Infomation 로깅 예시