본문 바로가기
C++ 200제/코딩 IT 정보

C# Stack Trace 닷넷 4.5부터 지원된 로그 출력 기능

by vicddory 2017. 2. 1.

C# Stack Trace. DotNET 4.5 지원 - Logging 기능


C++ 계열에는 편리한 로그 출력 기능이 있습니다. Stack Trace란 것으로, 예를 들면,


__LINE__ 키워드 이용 : 로그를 찍는 라인 넘버를 출력창에서 확인


20번 라인에서 __LINE__ 키워드를 이용하면 출력창에서 20이란 숫자가 확인되는 것입니다.


근데, 이런 편리한 기능이 C#엔 없느냐고 묻는다면 있다고 말씀드리겠습니다. 닷넷 프레임워크 4.5 미만 버전에선 Stack Trace와 StackFrame을 이용해 아래처럼 소스를 꾸밀 수 있었습니다.


1
2
3
4
5
6
7
8
StackTrace st = new StackTrace(new StackFrame(true));
Console.WriteLine(" Stack trace for current level: {0}", st.ToString());
 
StackFrame sf = st.GetFrame(0);
Console.WriteLine(" File: {0}", sf.GetFileName());
Console.WriteLine(" Method: {0}", sf.GetMethod().Name);
Console.WriteLine(" Line Number: {0}", sf.GetFileLineNumber());
Console.WriteLine(" Column Number: {0}", sf.GetFileColumnNumber());
cs


근데, 딱 보기에도 좀 길고 Stack Trace와 StackFrame의 객체를 하나씩 만들어야 한다는 건 많이 거슬리죠. 그래서 4.5 버전부터는 Caller Information 클래스가 추가되었습니다.


다만, 아직까진 지원되는 기능이 많지 않습니다.


  • CallerFilePathAttribute : 호출 함수가 포함된 파일의 전체 경로
  • CallerLineNumberAttribute : 함수를 호출한 라인 넘버
  • CallerMemberNameAttribute : 호출 함수의 이름


총 3개의 기능을 제공하고 있는데, 7개 이상의 주요 기능을 제공하는 C++에 비해선 아직 모자랍니다. 그래도 닷넷 프레임워크가 업데이트되면서 확장될 가능성은 아주 높다고 보입니다.


예제를 살펴보죠. 아래 코드는 MSDN에서 제공하는 것으로 꽤 직관적이라 이해하기 쉽습니다.


1
2
3
4
5
6
7
8
9
10
static public void TraceMessage(string message,
    [CallerMemberName] string memberName = "",
    [CallerFilePath] string sourceFilePath = "",
    [CallerLineNumber] int sourceLineNumber = 0)
{
    Console.WriteLine("message: " + message);
    Console.WriteLine("member name: " + memberName);
    Console.WriteLine("source file path: " + sourceFilePath);
    Console.WriteLine("source line number: " + sourceLineNumber);
}
cs


Stack Trace Caller Information[Stack Trace Caller Information]


아래는 전체 소스입니다. 이해하기 쉬워요.


Stack Trace Caller Information 소스[Stack Trace Caller Information 소스]




▷ 전체 소스


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Program
{
    static void Main(string[] args)
    {
        TestFunc();
    }
 
    static public void TestFunc()
    {
        TraceMessage("Caller information Test");
    }
 
    static public void TraceMessage(string message,
            [CallerMemberName] string memberName = "",
            [CallerFilePath] string sourceFilePath = "",
            [CallerLineNumber] int sourceLineNumber = 0)
    {
        Console.WriteLine("message: " + message);
        Console.WriteLine("member name: " + memberName);
        Console.WriteLine("source file path: " + sourceFilePath);
        Console.WriteLine("source line number: " + surceLineNumber);
    }
}
cs


C# Stack Trace. DotNET 4.5 지원 - Logging 기능

 written by vicddory

댓글