본문 바로가기

C#

C# Attribute 기반 로깅 시스템 구현

C#에서 Attribute를 활용하면 코드에 메타데이터를 부여해 편리하게 기능을 확장할 수 있습니다. 이번 글에서는 Attribute를 사용해 메서드 호출 시 자동으로 로그를 남기는 간단한 로깅 시스템을 구현하는 방법을 다룹니다.

1. Attribute 정의

먼저 로깅을 표시할 Attribute 클래스를 만듭니다.

[AttributeUsage(AttributeTargets.Method)]
public class LogAttribute : Attribute
{
}

2. Proxy를 이용한 메서드 감싸기

직접 호출 코드를 바꾸기 어렵기 때문에, DispatchProxy를 활용해 메서드 호출 전후에 로그를 찍도록 구현합니다.

using System.Reflection;

public class LoggingProxy : DispatchProxy
{
    public T Target { get; set; }

    protected override object Invoke(MethodInfo targetMethod, object[] args)
    {
        var isLog = targetMethod.GetCustomAttribute() != null;

        if (isLog)
            Console.WriteLine($"[Log] {targetMethod.Name} 호출 시작");

        var result = targetMethod.Invoke(Target, args);

        if (isLog)
            Console.WriteLine($"[Log] {targetMethod.Name} 호출 종료");

        return result;
    }
}

3. 사용 예시

인터페이스와 구현체를 작성하고, 프록시로 래핑해 사용해봅니다.

public interface ICalculator
{
    [Log]
    int Add(int x, int y);

    int Multiply(int x, int y);
}

public class Calculator : ICalculator
{
    public int Add(int x, int y) => x + y;
    public int Multiply(int x, int y) => x * y;
}

class Program
{
    static void Main()
    {
        var calculator = new Calculator();

        var proxy = LoggingProxy.Create>();
        (proxy as LoggingProxy).Target = calculator;

        Console.WriteLine(proxy.Add(3, 4));
        Console.WriteLine(proxy.Multiply(3, 4)); // 로그 없음
    }
}

이처럼 Add 메서드는 [Log] Attribute가 붙어 있어 호출 전후에 로그가 출력됩니다. Multiply 메서드는 로그가 찍히지 않습니다. Attribute 기반으로 필요한 메서드만 로깅할 수 있어 관리가 편리합니다.

더 발전시키면 로그 레벨, 파일 출력, 비동기 로깅 등 다양한 기능을 추가할 수 있습니다. 간단하지만 강력한 Attribute 기반 로깅 구현을 참고해보세요.