Visual C sharp의 추적 및 디버그

이 문서에서는 Visual C#에서 추적 및 디버그하는 방법을 설명하고 관련 정보를 설명하는 몇 가지 샘플 단계를 제공합니다.

원래 제품 버전: Visual C#
원본 KB 번호: 815788

요약

이 문서의 Microsoft Visual Basic .NET 버전은 Visual Basic .NET에서 추적 및 디버그 클래스 사용을 참조하세요.

이 문서에서는 .NET Framework 클래스 라이브러리 네임스페이스 시스템을 참조합니다. 진단 및 및 클래스를 사용하는 DebugTrace 방법을 설명합니다. 이러한 클래스는 .NET Framework 사용할 수 있습니다. 이러한 클래스를 사용하여 애플리케이션 개발 중 또는 프로덕션에 배포한 후 애플리케이션의 성능에 대한 정보를 제공할 수 있습니다. 이러한 클래스는 .NET Framework 사용할 수 있는 계측 기능의 한 부분일 뿐입니다.

요구 사항

다음 목록에서는 필요한 권장 하드웨어, 소프트웨어, 네트워크 인프라 및 서비스 팩을 간략하게 설명합니다.

  • Microsoft Windows
  • Microsoft Visual C#

또한 이 문서에서는 프로그램 디버깅에 익숙하다고 가정합니다.

기술에 대한 설명

디버그 클래스를 사용하여 샘플 만들기 섹션의 단계에서는 클래스를 사용하여 Debug 프로그램 실행에 대한 정보를 제공하는 콘솔 애플리케이션을 만드는 방법을 보여 줍니다.

프로그램이 실행되면 클래스의 Debug 메서드를 사용하여 프로그램 실행 순서를 모니터링하거나, 오작동을 감지하거나, 성능 측정 정보를 제공하는 데 도움이 되는 메시지를 생성할 수 있습니다. 기본적으로 클래스가 Debug 생성하는 메시지는 Visual Studio IDE(통합 개발 환경)의 출력 창에 표시됩니다.

샘플 코드는 메서드를 WriteLine 사용하여 줄 종결자 뒤에 메시지를 생성합니다. 이 메서드를 사용하여 메시지를 생성하면 각 메시지가 출력 창의 별도 줄에 표시됩니다.

클래스의 메서드를 AssertDebug 사용하면 지정된 조건이 false로 평가되는 경우에만 출력 창에 메시지가 표시됩니다. 메시지는 사용자에게 모달 대화 상자에도 나타납니다. 대화 상자에는 메시지, 프로젝트 이름 및 가 포함됩니다 Debug. Assert 문 번호입니다. 대화 상자에는 다음 세 가지 명령 단추도 포함됩니다.

  • 중단: 애플리케이션 실행이 중지됩니다.

  • 재시도: 애플리케이션이 디버그 모드로 전환됩니다.

  • 무시: 애플리케이션이 진행됩니다. 애플리케이션을 계속하려면 먼저 사용자가 이러한 단추 중 하나를 클릭해야 합니다.

출력 창 이외의 대상으로 클래스의 Debug 출력을 직접 지정할 수도 있습니다. 클래스에는 Debug 개체를 포함하는 Listener 수신기 컬렉션이 있습니다.

각 수신기 개체는 출력을 Debug 모니터링하고 출력을 지정된 대상으로 전달합니다.

수신기 컬렉션의 각 수신기는 클래스에서 생성하는 모든 출력을 Debug 받습니다. 클래스를 TextWriterTraceListener 사용하여 개체를 정의 Listener 합니다. 해당 생성자를 통해 클래스의 대상을 TextWriterTraceListener 지정할 수 있습니다.

몇 가지 가능한 출력 대상에는 다음이 포함됩니다.

  • 속성을 사용하여 콘솔 창입니다 System.Console.Out .
  • 문을 사용하여 텍스트(.txt) 파일입니다 System.IO.File.CreateText("FileName.txt") . 개체를 TextWriterTraceListener 만든 후에는 개체 Debug를 에 추가해야 합니다. 출력을 받을 Debug 수신기 컬렉션입니다.

디버그 클래스를 사용하여 샘플 만들기

  1. Visual Studio 또는 Visual C# Express Edition을 시작합니다.

  2. conInfo라는 새 Visual C# 콘솔 애플리케이션 프로젝트를 만듭니다. Class1은 Visual Studio .NET에서 만들어집니다. Program.cs Visual Studio 2005에서 만들어집니다.

  3. Class1 또는 Program.cs 맨 위에 다음 네임스페이스를 추가합니다.

    using System.Diagnostics;
    
  4. 제품에 대한 정보를 포함하도록 변수를 초기화하려면 Main 메서드에 다음 선언 문을 추가합니다.

    string sProdName = "Widget";
    int iUnitQty = 100;
    double dUnitCost = 1.03;
    
  5. 클래스가 메서드의 첫 번째 입력 매개 변수로 생성하는 메시지를 지정합니다 WriteLine . Ctrl+Alt+O 키 조합을 눌러 출력 창이 표시되는지 확인합니다.

    Debug.WriteLine("Debug Information-Product Starting ");
    
  6. 가독성을 위해 메서드를 Indent 사용하여 출력 창에서 후속 메시지를 들여쓰기합니다.

    Debug.Indent();
    
  7. 선택한 변수의 콘텐츠를 표시하려면 다음과 같이 메서드를 WriteLine 사용합니다.

    Debug.WriteLine("The product name is " + sProdName);
    Debug.WriteLine("The available units on hand are" + iUnitQty.ToString());
    Debug.WriteLine("The per unit cost is " + dUnitCost.ToString());
    
  8. 메서드를 WriteLine 사용하여 기존 개체의 네임스페이스 및 클래스 이름을 표시할 수도 있습니다. 예를 들어 다음 코드는 출력 창에 System.Xml.XmlDocument 네임스페이스를 표시합니다.

    System.Xml.XmlDocument oxml = new System.Xml.XmlDocument();
    Debug.WriteLine(oxml);
    
  9. 출력을 구성하려면 범주를 메서드의 선택적 두 번째 입력 매개 변수로 포함할 WriteLine 수 있습니다. 범주를 지정하는 경우 출력 창 메시지의 형식은 "category: message"입니다. 예를 들어 다음 코드의 첫 번째 줄에는 출력 창에 "필드: 제품 이름은 위젯"이 표시됩니다.

    Debug.WriteLine("The product name is " + sProdName,"Field");
    Debug.WriteLine("The units on hand are" + iUnitQty,"Field");
    Debug.WriteLine("The per unit cost is" + dUnitCost.ToString(),"Field");
    Debug.WriteLine("Total Cost is " + (iUnitQty * dUnitCost),"Calc");
    
  10. 출력 창은 지정된 조건이 클래스의 Debug 메서드를 사용하여 WriteLineIf true로 평가되는 경우에만 메시지를 표시할 수 있습니다. 계산할 조건은 메서드의 첫 번째 입력 매개 변수 WriteLineIf 입니다. 의 WriteLineIf 두 번째 매개 변수는 첫 번째 매개 변수의 조건이 true로 평가되는 경우에만 표시되는 메시지입니다.

    Debug.WriteLineIf(iUnitQty > 50, "This message WILL appear");
    Debug.WriteLineIf(iUnitQty < 50, "This message will NOT appear");
    
  11. 지정된 조건이 false로 평가되는 경우에만 출력 창에 메시지가 표시되도록 클래스의 Debug Assert 메서드를 사용합니다.

    Debug.Assert(dUnitCost > 1, "Message will NOT appear");
    Debug.Assert(dUnitCost < 1, "Message will appear since dUnitcost < 1 is false");
    
  12. TextWriterTraceListener 콘솔 창(tr1) 및 Output.txt (tr2)라는 텍스트 파일의 개체를 만든 다음, Debug Listeners 컬렉션에 각 개체를 추가합니다.

    TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out);
    Debug.Listeners.Add(tr1);
    
    TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("Output.txt"));
    Debug.Listeners.Add(tr2);
    
  13. 가독성을 위해 메서드를 Unindent 사용하여 클래스가 생성하는 후속 메시지에 Debug 대한 들여쓰기를 제거합니다. 및 메서드를 IndentUnindent 함께 사용하면 판독기가 출력을 그룹으로 구분할 수 있습니다.

    Debug.Unindent();
    Debug.WriteLine("Debug Information-Product Ending");
    
  14. Listener 개체가 모든 출력을 받도록 하려면 클래스 버퍼에 대한 Flush 메서드를 Debug 호출합니다.

    Debug.Flush();
    

추적 클래스 사용

클래스를 Trace 사용하여 애플리케이션 실행을 모니터링하는 메시지를 생성할 수도 있습니다. 및 Debug 클래스는 Trace 다음을 포함하여 출력을 생성하기 위해 동일한 메서드의 대부분을 공유합니다.

  • Writeline
  • WriteLineIf
  • 들여쓰기
  • Unindent
  • 주장
  • 플러시

및 클래스를 TraceDebug 동일한 애플리케이션에서 개별적으로 또는 함께 사용할 수 있습니다. 디버그 솔루션 구성 프로젝트에서 및 Debug 출력이 모두 Trace 활성 상태입니다. 이 프로젝트는 이러한 두 클래스에서 모든 Listener 개체로 출력을 생성합니다. 그러나 릴리스 솔루션 구성 프로젝트는 클래스의 Trace 출력만 생성합니다. 릴리스 솔루션 구성 프로젝트는 클래스 Debug 메서드 호출을 무시합니다.

Trace.WriteLine("Trace Information-Product Starting ");
Trace.Indent();

Trace.WriteLine("The product name is "+sProdName);
Trace.WriteLine("The product name is"+sProdName,"Field" );
Trace.WriteLineIf(iUnitQty > 50, "This message WILL appear");
Trace.Assert(dUnitCost > 1, "Message will NOT appear");

Trace.Unindent();
Trace.WriteLine("Trace Information-Product Ending");

Trace.Flush();

Console.ReadLine();

작동하는지 확인합니다.

  1. 디버그가 현재 솔루션 구성인지 확인합니다.

  2. 솔루션 탐색기 창이 표시되지 않으면 Ctrl+Alt+L 키 조합을 눌러 이 창을 표시합니다.

  3. conInfo를 마우스 오른쪽 단추로 클릭한 다음 속성을 클릭합니다.

  4. conInfo 속성 페이지의 왼쪽 창에 있는 구성 폴더 아래에서 화살표가 디버깅을 가리키는지 확인합니다.

    참고

    Visual C# 2005 및 Visual C# 2005 Express Edition에서 conInfo 페이지에서 디버그를 클릭합니다.

  5. 구성 폴더 위의 구성 드롭다운 목록 상자에서 활성(디버그) 또는 디버그를 클릭한 다음 확인을 클릭합니다. Visual C# 2005 및 Visual C# 2005 Express Edition에서 버그 페이지의 구성 드롭다운 목록 상자에서 활성(디버그) 또는 버그를 클릭한 다음 파일 메뉴에서 저장을 클릭합니다.

  6. Ctrl+Alt+O를 눌러 출력 창을 표시합니다.

  7. F5 키를 눌러 코드를 실행합니다. 어설션 실패 대화 상자가 나타나면 무시를 클릭합니다.

  8. 콘솔 창에서 Enter 키를 누릅니. 프로그램이 완료되고 출력 창에 다음과 유사한 출력이 표시됩니다.

    Debug Information-Product Starting
    The product name is Widget
    The available units on hand are100
    The per unit cost is 1.03
    System.Xml.XmlDocument
    Field: The product name is Widget
    Field: The units on hand are100
    Field: The per unit cost is1.03
    Calc: Total Cost is 103
    This message WILL appear
    ---- DEBUG ASSERTION FAILED ----
    ---- Assert Short Message ----
    Message will appear since dUnitcost < 1 is false
    ---- Assert Long Message ----
    
    at Class1.Main(String[] args) <%Path%>\class1.cs(34)
    
    The product name is Widget
    The available units on hand are100
    The per unit cost is 1.03
    Debug Information-Product Ending
    Trace Information-Product Starting
    The product name is Widget
    Field: The product name isWidget
    This message WILL appear
    Trace Information-Product Ending
    
  9. 콘솔 창과 Output.txt 파일에는 다음 출력이 표시됩니다.

    The product name is Widget
    The available units on hand are 100
    The per unit cost is 1.03
    Debug Information-Product Ending
    Trace Information-Product Starting
    The product name is Widget
    Field: The product name is Widget
    This message WILL appear
    Trace Information-Product Ending
    

참고

Output.txt 파일은 conInfo 실행 파일(conInfo.exe)과 동일한 디렉터리에 있습니다. 일반적으로 프로젝트 원본이 저장되는 \bin 폴더입니다. 기본적으로 는 입니다 C:\Documents and Settings\User login\My Documents\Visual Studio Projects\conInfo\bin. Visual C# 2005 및 Visual C# 2005 Express Edition에서 Output.txt 파일은 폴더 C:\Documents and Settings\User login\My Documents\Visual Studio 2005\Projects\conInfo\conInfo\bin\Debug에 있습니다.

전체 코드 목록

using System;
using System.Diagnostics;

class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        string sProdName = "Widget";
        int iUnitQty = 100;
        double dUnitCost = 1.03;
        Debug.WriteLine("Debug Information-Product Starting ");
        Debug.Indent();
        Debug.WriteLine("The product name is "+sProdName);
        Debug.WriteLine("The available units on hand are"+iUnitQty.ToString());
        Debug.WriteLine("The per unit cost is "+ dUnitCost.ToString());

        System.Xml.XmlDocument oxml = new System.Xml.XmlDocument();
        Debug.WriteLine(oxml);

        Debug.WriteLine("The product name is "+sProdName,"Field");
        Debug.WriteLine("The units on hand are"+iUnitQty,"Field");
        Debug.WriteLine("The per unit cost is"+dUnitCost.ToString(),"Field");
        Debug.WriteLine("Total Cost is "+(iUnitQty * dUnitCost),"Calc");

        Debug.WriteLineIf(iUnitQty > 50, "This message WILL appear");
        Debug.WriteLineIf(iUnitQty < 50, "This message will NOT appear");

        Debug.Assert(dUnitCost > 1, "Message will NOT appear");
        Debug.Assert(dUnitCost < 1, "Message will appear since dUnitcost < 1 is false");

        TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out);
        Debug.Listeners.Add(tr1);

        TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("Output.txt"));
        Debug.Listeners.Add(tr2);

        Debug.WriteLine("The product name is "+sProdName);
        Debug.WriteLine("The available units on hand are"+iUnitQty);
        Debug.WriteLine("The per unit cost is "+dUnitCost);
        Debug.Unindent();
        Debug.WriteLine("Debug Information-Product Ending");
        Debug.Flush();

        Trace.WriteLine("Trace Information-Product Starting ");
        Trace.Indent();

        Trace.WriteLine("The product name is "+sProdName);
        Trace.WriteLine("The product name is"+sProdName,"Field" );
        Trace.WriteLineIf(iUnitQty > 50, "This message WILL appear");
        Trace.Assert(dUnitCost > 1, "Message will NOT appear");

        Trace.Unindent();
        Trace.WriteLine("Trace Information-Product Ending");

        Trace.Flush();

        Console.ReadLine();
    }
}

문제 해결

  • 솔루션 구성 유형이 Release Debug 이면 클래스 출력이 무시됩니다.

  • 특정 대상에 대한 클래스를 TextWriterTraceListener 만든 후 및 TextWriterTraceListener 클래스에서 Trace 출력을 Debug 받습니다. 이는 의 메서드 Trace 를 사용하는지 또는 클래스를 클래스에 AddDebug 추가할 TextWriterTraceListenerListeners 지 여부에 관계없이 발생합니다.

  • 및 클래스에서 Trace 동일한 대상에 대한 개체를 추가하는 Listeners 경우 출력의 생성 여부에 TraceDebug 관계없이 각 출력 줄이 중복됩니다.Debug

    TextWriterTraceListener myWriter = new TextWriterTraceListener(System.Console.Out);
    Debug.Listeners.Add(myWriter);
    
    TextWriterTraceListener myCreator = new TextWriterTraceListener(System.Console.Out);
    Trace.Listeners.Add(myCreator);
    

참조