DefaultTraceListener 클래스

정의

추적의 기본 출력 메서드 및 동작을 제공합니다.

public ref class DefaultTraceListener : System::Diagnostics::TraceListener
public class DefaultTraceListener : System.Diagnostics.TraceListener
[System.Runtime.InteropServices.ComVisible(false)]
public class DefaultTraceListener : System.Diagnostics.TraceListener
type DefaultTraceListener = class
    inherit TraceListener
[<System.Runtime.InteropServices.ComVisible(false)>]
type DefaultTraceListener = class
    inherit TraceListener
Public Class DefaultTraceListener
Inherits TraceListener
상속
DefaultTraceListener
상속
DefaultTraceListener
특성

예제

다음 코드 예제에서는 확률 및 통계에 사용되는 값인 이항 계수를 계산합니다. 이 예제에서는 를 DefaultTraceListener 사용하여 결과 및 로그 오류를 추적합니다. 새 DefaultTraceListener를 만들고 컬렉션에 Trace.Listeners 추가하고 속성을 명령줄 인수에 지정된 로그 파일로 설정합니다 LogFileName .

입력 매개 변수를 처리하는 동안 오류가 감지되거나 함수가 CalcBinomial 예외를 throw하는 경우 메서드가 Fail 로깅하고 오류 메시지를 표시합니다. 속성false이 이 AssertUiEnabled 면 오류 메시지도 콘솔에 기록됩니다. 결과가 성공적으로 계산되면 및 WriteLine(String) 메서드는 Write(String) 결과를 로그 파일에 씁니다.

, WriteWriteLine 메서드를 Fail사용하면 추적 정보가 에만 DefaultTraceListener기록됩니다. 컬렉션의 모든 수신기에 Trace.Listeners 추적 정보를 쓰려면 클래스의 Fail, WriteWriteLine 메서드를 Trace 사용합니다.

using System;
using System.Diagnostics;
using Microsoft.VisualBasic;

class Binomial
{

    // args(0) is the number of possibilities for binomial coefficients.
    // args(1) is the file specification for the trace log file.
    public static void Main(string[] args)
    {

        decimal possibilities;
        decimal iter;

        // Remove the original default trace listener.
        Trace.Listeners.RemoveAt(0);

        // Create and add a new default trace listener.
        DefaultTraceListener defaultListener;
        defaultListener = new DefaultTraceListener();
        Trace.Listeners.Add(defaultListener);

        // Assign the log file specification from the command line, if entered.
        if (args.Length>=2)
        {
            defaultListener.LogFileName = args[1];
        }

        // Validate the number of possibilities argument.
        if (args.Length>=1)

            // Verify that the argument is a number within the correct range.
        {
            try
            {
                const decimal MAX_POSSIBILITIES = 99;
                possibilities = Decimal.Parse(args[0]);
                if (possibilities<0||possibilities>MAX_POSSIBILITIES)
                {
                    throw new Exception(String.Format("The number of possibilities must " +
                        "be in the range 0..{0}.", MAX_POSSIBILITIES));
                }
            }
            catch(Exception ex)
            {
                string failMessage = String.Format("\"{0}\" " +
                    "is not a valid number of possibilities.", args[0]);
                defaultListener.Fail(failMessage, ex.Message);
                if (!defaultListener.AssertUiEnabled)
                {
                    Console.WriteLine(failMessage+ "\n" +ex.Message);
                }
                return;
            }
        }
        else
        {
            // Report that the required argument is not present.
            const string ENTER_PARAM = "Enter the number of " +
                      "possibilities as a command line argument.";
            defaultListener.Fail(ENTER_PARAM);
            if (!defaultListener.AssertUiEnabled)
            {
                Console.WriteLine(ENTER_PARAM);
            }
            return;
        }

        for(iter=0; iter<=possibilities; iter++)
        {
            decimal result;
            string binomial;

            // Compute the next binomial coefficient and handle all exceptions.
            try
            {
                result = CalcBinomial(possibilities, iter);
            }
            catch(Exception ex)
            {
                string failMessage = String.Format("An exception was raised when " +
                    "calculating Binomial( {0}, {1} ).", possibilities, iter);
                defaultListener.Fail(failMessage, ex.Message);
                if (!defaultListener.AssertUiEnabled)
                {
                    Console.WriteLine(failMessage+ "\n" +ex.Message);
                }
                return;
            }

            // Format the trace and console output.
            binomial = String.Format("Binomial( {0}, {1} ) = ", possibilities, iter);
            defaultListener.Write(binomial);
            defaultListener.WriteLine(result.ToString());
            Console.WriteLine("{0} {1}", binomial, result);
        }
    }

    public static decimal CalcBinomial(decimal possibilities, decimal outcomes)
    {

        // Calculate a binomial coefficient, and minimize the chance of overflow.
        decimal result = 1;
        decimal iter;
        for(iter=1; iter<=possibilities-outcomes; iter++)
        {
            result *= outcomes+iter;
            result /= iter;
        }
        return result;
    }
}
Imports System.Diagnostics

Module Binomial

    ' args(0) is the number of possibilities for binomial coefficients.
    ' args(1) is the file specification for the trace log file.
    Sub Main(ByVal args() As String)

        Dim possibilities As Decimal
        Dim iter As Decimal

        ' Remove the original default trace listener.
        Trace.Listeners.RemoveAt(0)

        ' Create and add a new default trace listener.
        Dim defaultListener As DefaultTraceListener
        defaultListener = New DefaultTraceListener
        Trace.Listeners.Add(defaultListener)

        ' Assign the log file specification from the command line, if entered.
        If args.Length >= 2 Then
            defaultListener.LogFileName = args(1)
        End If

        ' Validate the number of possibilities argument.
        If args.Length >= 1 Then

            ' Verify that the argument is a number within the correct range.
            Try
                Const MAX_POSSIBILITIES As Decimal = 99
                possibilities = Decimal.Parse(args(0))
                If possibilities < 0 Or possibilities > MAX_POSSIBILITIES Then
                    Throw New Exception( _
                        String.Format("The number of possibilities must " & _
                            "be in the range 0..{0}.", MAX_POSSIBILITIES))
                End If
            Catch ex As Exception
                Dim failMessage As String = String.Format("""{0}"" " & _
                    "is not a valid number of possibilities.", args(0))
                defaultListener.Fail(failMessage, ex.Message)
                If Not defaultListener.AssertUiEnabled Then
                    Console.WriteLine(failMessage & vbCrLf & ex.Message)
                End If
                Return
            End Try
        Else
            ' Report that the required argument is not present.
            Const ENTER_PARAM As String = "Enter the number of " & _
                "possibilities as a command line argument."
            defaultListener.Fail(ENTER_PARAM)
            If Not defaultListener.AssertUiEnabled Then
                Console.WriteLine(ENTER_PARAM)
            End If
            Return
        End If

        For iter = 0 To possibilities
            Dim result As Decimal
            Dim binomial As String

            ' Compute the next binomial coefficient and handle all exceptions.
            Try
                result = CalcBinomial(possibilities, iter)
            Catch ex As Exception
                Dim failMessage As String = String.Format( _
                        "An exception was raised when " & _
                        "calculating Binomial( {0}, {1} ).", _
                        possibilities, iter)
                defaultListener.Fail(failmessage, ex.Message)
                If Not defaultListener.AssertUiEnabled Then
                    Console.WriteLine(failMessage & vbCrLf & ex.Message)
                End If
                Return
            End Try

            ' Format the trace and console output.
            binomial = String.Format("Binomial( {0}, {1} ) = ", _
                            possibilities, iter)
            defaultListener.Write(binomial)
            defaultListener.WriteLine(result.ToString)
            Console.WriteLine("{0} {1}", binomial, result)
        Next
    End Sub

    Function CalcBinomial(ByVal possibilities As Decimal, _
                        ByVal outcomes As Decimal) As Decimal

        ' Calculate a binomial coefficient, and minimize the chance of overflow.
        Dim result As Decimal = 1
        Dim iter As Decimal
        For iter = 1 To possibilities - outcomes
            result *= outcomes + iter
            result /= iter
        Next
        Return result
    End Function
End Module

설명

이 클래스의 인스턴스는 및 Trace.Listeners 컬렉션에 Debug.Listeners 자동으로 추가됩니다. 두 번째 DefaultTraceListener 를 명시적으로 추가하면 디버거 출력 창에서 중복 메시지가 발생하고 어설션에 대한 메시지 상자가 중복됩니다.

기본적으로 및 WriteLine 메서드는 Write 메시지를 Win32 OutputDebugString 함수 및 메서드로 내보낸다Debugger.Log.

합니다 Fail 메서드를 기본적으로 메시지 상자를 표시 애플리케이션 사용자 인터페이스 모드에서 실행 중인 경우;도 사용 하 여 메시지를 내보내는 WriteLine합니다.

참고

Fail 메서드 호출에 대한 Assert 메시지 상자의 표시는 의 DefaultTraceListener존재에 따라 달라집니다. 가 DefaultTraceListener 컬렉션에 Listeners 없으면 메시지 상자가 표시되지 않습니다. 은 DefaultTraceListener 속성(System.Diagnostics.Trace.Listeners.Clear())에서 Listeners 메서드를 Clear 호출하여 제거할 수 있습니다. .NET Framework 앱의 경우 앱의 <구성 파일에서 clear> 요소<remove> 요소를 사용할 수도 있습니다.

추적 수신기를 사용하려면 추적 또는 디버깅을 사용하도록 설정해야 합니다. 다음 구문은 특정 컴파일러입니다. C# 또는 Visual Basic 이외의 컴파일러를 사용 하면 컴파일러에 대 한 설명서를 참조 합니다.

  • C#에서 디버깅을 사용하도록 설정하려면 코드를 컴파일할 때 컴파일러 명령줄에 플래그를 추가 /d:DEBUG 하거나 파일 맨 위에 를 추가 #define DEBUG 합니다. Visual Basic에서 추가 된 /d:DEBUG=True 컴파일러 명령줄 플래그입니다.

  • C#에서 추적을 사용 하려면 추가 합니다 /d:TRACE 코드를 컴파일할 때 컴파일러 명령줄 플래그 #define TRACE 파일의 맨 위로 이동 합니다. Visual Basic에서 추가 된 /d:TRACE=True 컴파일러 명령줄 플래그입니다.

.NET Framework 앱의 경우 애플리케이션 이름에 해당하는 구성 파일을 편집하여 추적 수신기를 추가할 수 있습니다. 이 파일에 수신기를 추가, 해당 형식을 설정 하 고 해당 매개 변수를 설정, 수신기를 제거 하거나 지울 수 애플리케이션에서 이전에 설정한 모든 수신기입니다. 구성 파일의 형식은 다음 예제와 유사하게 지정해야 합니다.

<configuration>  
<system.diagnostics>  
  <trace autoflush="false" indentsize="4">  
    <listeners>  
      <remove name="Default" />  
      <add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="c:\myListener.log" />  
    </listeners>  
  </trace>  
</system.diagnostics>  
</configuration>  

생성자

DefaultTraceListener()

DefaultTraceListener 속성 값으로 "Default"를 사용하여 Name 클래스의 새 인스턴스를 초기화합니다.

속성

AssertUiEnabled

애플리케이션이 사용자 인터페이스 모드에서 실행되고 있는지 여부를 나타내는 값을 가져오거나 설정합니다.

Attributes

애플리케이션 구성 파일에 정의된 사용자 지정 추적 수신기 특성을 가져옵니다.

(다음에서 상속됨 TraceListener)
Filter

추적 수신기의 추적 필터를 가져오거나 설정합니다.

(다음에서 상속됨 TraceListener)
IndentLevel

들여쓰기 수준을 가져오거나 설정합니다.

(다음에서 상속됨 TraceListener)
IndentSize

들여쓰기의 공백 수를 가져오거나 설정합니다.

(다음에서 상속됨 TraceListener)
IsThreadSafe

추적 수신기가 스레드로부터 안전한지 여부를 나타내는 값을 가져옵니다.

(다음에서 상속됨 TraceListener)
LogFileName

추적 또는 디버그 메시지를 쓸 로그 파일 이름을 가져오거나 설정합니다.

Name

TraceListener의 이름을 가져오거나 설정합니다.

(다음에서 상속됨 TraceListener)
NeedIndent

출력의 들여쓰기 여부를 나타내는 값을 가져오거나 설정합니다.

(다음에서 상속됨 TraceListener)
TraceOutputOptions

추적 출력 옵션을 가져오거나 설정합니다.

(다음에서 상속됨 TraceListener)

메서드

Close()

파생 클래스에서 재정의할 때 더 이상 추적 또는 디버깅 출력을 받지 않도록 출력 스트림을 닫습니다.

(다음에서 상속됨 TraceListener)
CreateObjRef(Type)

원격 개체와 통신하는 데 사용되는 프록시 생성에 필요한 모든 관련 정보가 들어 있는 개체를 만듭니다.

(다음에서 상속됨 MarshalByRefObject)
Dispose()

TraceListener에서 사용하는 모든 리소스를 해제합니다.

(다음에서 상속됨 TraceListener)
Dispose(Boolean)

TraceListener에서 사용하는 관리되지 않는 리소스를 해제하고, 관리되는 리소스를 선택적으로 해제할 수 있습니다.

(다음에서 상속됨 TraceListener)
Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
Fail(String)

항상 실패하는 어설션에 대한 메시지 및 스택 추적을 내보내거나 표시합니다.

Fail(String, String)

항상 실패하는 어설션에 대한 자세한 메시지 및 스택 추적을 내보내거나 표시합니다.

Flush()

파생 클래스에서 재정의할 때 출력 버퍼를 플러시합니다.

(다음에서 상속됨 TraceListener)
GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetLifetimeService()
사용되지 않음.

이 인스턴스의 수명 정책을 제어하는 현재의 수명 서비스 개체를 검색합니다.

(다음에서 상속됨 MarshalByRefObject)
GetSupportedAttributes()

추적 수신기에서 지원하는 사용자 지정 특성을 가져옵니다.

(다음에서 상속됨 TraceListener)
GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
InitializeLifetimeService()
사용되지 않음.

이 인스턴스의 수명 정책을 제어하는 수명 서비스 개체를 가져옵니다.

(다음에서 상속됨 MarshalByRefObject)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
MemberwiseClone(Boolean)

현재 MarshalByRefObject 개체의 단순 복사본을 만듭니다.

(다음에서 상속됨 MarshalByRefObject)
ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)
TraceData(TraceEventCache, String, TraceEventType, Int32, Object)

추적 정보, 데이터 개체 및 이벤트 정보를 수신기별 출력에 씁니다.

(다음에서 상속됨 TraceListener)
TraceData(TraceEventCache, String, TraceEventType, Int32, Object[])

추적 정보, 데이터 개체 배열 및 이벤트 정보를 수신기별 출력에 씁니다.

(다음에서 상속됨 TraceListener)
TraceEvent(TraceEventCache, String, TraceEventType, Int32)

추적 및 이벤트 정보를 수신기별 출력에 씁니다.

(다음에서 상속됨 TraceListener)
TraceEvent(TraceEventCache, String, TraceEventType, Int32, String)

추적 정보, 메시지 및 이벤트 정보를 수신기별 출력에 씁니다.

(다음에서 상속됨 TraceListener)
TraceEvent(TraceEventCache, String, TraceEventType, Int32, String, Object[])

추적 정보, 서식 지정된 개체 배열 및 이벤트 정보를 수신기별 출력에 씁니다.

(다음에서 상속됨 TraceListener)
TraceTransfer(TraceEventCache, String, Int32, String, Guid)

추적 정보, 메시지, 관련 작업 ID 및 이벤트 정보를 수신기별 출력에 씁니다.

(다음에서 상속됨 TraceListener)
Write(Object)

ToString() 클래스를 구현할 때 생성한 수신기에 개체의 TraceListener 메서드 값을 씁니다.

(다음에서 상속됨 TraceListener)
Write(Object, String)

ToString() 클래스를 구현할 때 생성한 수신기에 범주 이름 및 개체의 TraceListener 메서드 값을 씁니다.

(다음에서 상속됨 TraceListener)
Write(String)

OutputDebugString 함수와 Log(Int32, String, String) 메서드에 출력합니다.

Write(String, String)

TraceListener 클래스를 구현할 때 생성한 수신기에 범주 이름 및 메시지를 씁니다.

(다음에서 상속됨 TraceListener)
WriteIndent()

이 클래스를 구현할 때 생성한 수신기에 들여쓰기를 하고 NeedIndent 속성을 false로 다시 설정합니다.

(다음에서 상속됨 TraceListener)
WriteLine(Object)

ToString() 클래스를 구현할 때 생성한 수신기에 개체의 TraceListener 메서드 값을 쓴 다음 줄 종결자를 씁니다.

(다음에서 상속됨 TraceListener)
WriteLine(Object, String)

ToString() 클래스를 구현할 때 생성한 수신기에 범주 이름 및 개체의 TraceListener 메서드 값을 쓴 다음 줄 종결자를 씁니다.

(다음에서 상속됨 TraceListener)
WriteLine(String)

캐리지 리턴과 줄 바꿈(\r\n)이 다음에 오도록 OutputDebugString 함수와 Log(Int32, String, String) 메서드에 출력합니다.

WriteLine(String, String)

TraceListener 클래스를 구현할 때 생성한 수신기에 범주 이름 및 메시지를 쓴 다음 줄 종결자를 씁니다.

(다음에서 상속됨 TraceListener)

적용 대상

스레드 보안

이 클래스는 스레드로부터 안전합니다.

추가 정보