C#

C# 기초부터 고급까지 Chapter 2.5. 파일 입출력, 로그 남기기 – NLog, Serilog 예제

Juan_ 2025. 4. 30. 21:08
728x90

📘 Chapter 2.5: 파일 입출력, 로그 남기기 – NLog, Serilog 예제


✅ 이 챕터에서 배울 것

실무에서 로그 남기는 건 그냥 옵션이 아니라 생명줄이다.

뭔 일 터졌을 때 로그가 없으면 원인 분석 자체가 불가능해진다!

  • 파일 입출력 기본
  • 스트림 처리 (StreamReader/Writer)
  • 실무 로깅 라이브러리: NLogSerilog
  • 각 라이브러리 비교, 설정법, 사용 예제
  • 실전 상황별 로그 패턴

1️⃣ 파일 입출력 (File I/O) 기본


📦 파일 쓰기

string path = "log.txt";
File.WriteAllText(path, "로그 한 줄!");

📦 파일에 줄 단위로 추가 쓰기

File.AppendAllText(path, "추가 로그\n");

📖 파일 읽기

string content = File.ReadAllText(path);
Console.WriteLine(content);

✅ 이 방식은 간단하지만,

  • 파일이 커지면 메모리 문제
  • 동시 접근 시 충돌 가능

👉 그래서 실무에서는 StreamWriter, StreamReader 또는 전용 로깅 라이브러리 사용!


2️⃣ Stream 기반 쓰기/읽기


✏️ StreamWriter로 로그 쓰기

using (StreamWriter sw = new StreamWriter("log.txt", append: true))
{
    sw.WriteLine($"[{DateTime.Now}] 시스템 로그 기록");
}
  • ✅ append: true면 기존 내용에 이어서 쓴다
  • ✅ using 블록은 자동으로 리소스를 닫아준다!

📖 StreamReader로 읽기

using (StreamReader sr = new StreamReader("log.txt"))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}
  • ✅ 줄 단위로 읽는다!
  • ✅ 실제 로그 분석할 때 요걸로 로딩함!

3️⃣ 실무는 그냥 로깅 라이브러리 써라


NLog / Serilog → .NET에서 가장 많이 쓰이는 두 개다

라이브러리 특징
NLog 오래된 고전, 설정파일 기반, 안정성 높음
Serilog 구조화 로그, 콘솔+파일+Elastic 통합 최고

요즘은 Serilog 많이 씀!


4️⃣ NLog 사용 예제


1️⃣ NuGet 설치

dotnet add package NLog
dotnet add package NLog.Config

2️⃣ 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="logfile" xsi:type="File" fileName="log.txt" />
    <target name="logconsole" xsi:type="Console" />
  </targets>

  <rules>
    <logger name="*" minlevel="Info" writeTo="logfile,logconsole" />
  </rules>

</nlog>

3️⃣ 사용 코드

using NLog;

var logger = LogManager.GetCurrentClassLogger();

logger.Info("정보 로그 남김");
logger.Warn("경고 로그 남김");
logger.Error("에러 로그 남김");

5️⃣ Serilog 사용 예제 (추천)


1️⃣ NuGet 설치

dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.File

2️⃣ Program.cs 설정 (.NET 6 이상)

using Serilog;

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .WriteTo.Console()
    .WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day)
    .CreateLogger();

builder.Host.UseSerilog();

3️⃣ 사용 코드

Log.Information("서비스가 시작되었습니다");
Log.Warning("디스크 용량이 부족합니다");
Log.Error("예외 발생: {Error}", ex.Message);

✅ 템플릿처럼 {Error} 이런 식으로 구조화된 로그도 남길 수 있다!


6️⃣ 실무 로그 남길 때 꿀팁


로그 수준 설명
Trace 가장 상세한 디버그용 로그
Debug 개발 중 내부 확인용
Info 시스템 상태 변화 기록
Warn 문제 가능성 있는 경고
Error 예외 발생, 기능 실패
Fatal 시스템 전체 영향을 줄 심각한 에러

✅ 실무에서는

  • Info + Warn + Error 조합으로 대부분 처리
  • 로그 경로 + 형식 + 롤링(날짜별 분할)은 반드시 세팅

✅ 최종 요약


항목 설명
File I/O StreamWriter/Reader로 입출력 가능
NLog XML 설정 중심, 전통적 스타일
Serilog 구조화 로그, 성능 및 유연성 최고
로그 수준 Trace → Debug → Info → Warn → Error → Fatal
실무 포인트 예외 + 흐름 + 경고 3단계 로그는 꼭 남겨라!

📢 다음 챕터 예고 🎓

다음 챕터 주제
Chapter 2.6 Configuration 관리 – appsettings.json 구조와 환경별 분리
728x90