My.Application.Log.WriteEntry()如何与System.Diagnostics.Trace.WriteLine()相关

时间:2012-02-01 02:50:15

标签: .net vb.net logging

WriteEntry与Writeline有完全不同的签名。还有一个My.Application.Log.WriteException()。当我以编程方式添加侦听器时,WriteEntry不起作用。

 Trace.Listeners.Add(New Logging.FileLogTraceListener("stuff") With { _
                            .Append = False, _
                            .AutoFlush = True, _
                            .DiskSpaceExhaustedBehavior = Logging.DiskSpaceExhaustedOption.DiscardMessages, _
                            .Location = Logging.LogFileLocation.ExecutableDirectory, _
                            .TraceOutputOptions = TraceOptions.DateTime, _
                            .BaseFileName = GetExecutingAssembly.GetName.Name & "_" & Date.Now.ToString(ISO_LogFileNameFormat)})

有人可以解释这些功能之间的关系吗?

1 个答案:

答案 0 :(得分:3)

要了解WriteEntry和Writeline之间的区别,请使用Reflector或ILSpy并向下钻取以查看内部实现。 System.Diagnostic.Trace.WriteLine:

Public Shared Sub WriteLine(ByVal value As Object)
    If TraceInternal.UseGlobalLock Then
        SyncLock TraceInternal.critSec
            Dim listener As TraceListener
            For Each listener In TraceInternal.Listeners
                listener.WriteLine(value)
                If TraceInternal.AutoFlush Then
                    listener.Flush
                End If
            Next
            Return
        End SyncLock
    End If
    Dim listener2 As TraceListener
    For Each listener2 In TraceInternal.Listeners
        If Not listener2.IsThreadSafe Then
            SyncLock listener2
                listener2.WriteLine(value)
                If TraceInternal.AutoFlush Then
                    listener2.Flush
                End If
                Continue For
            End SyncLock
        End If
        listener2.WriteLine(value)
        If TraceInternal.AutoFlush Then
            listener2.Flush
        End If
    Next
End Sub

My.Application.Log.WriteEntry只是一个LOP语法,但它真正指向名称空间Microsoft.VisualBasic.Logging.Log.WriteEntry:

Public Sub WriteEntry(ByVal message As String, ByVal severity As TraceEventType, ByVal id As Integer)
    If (message Is Nothing) Then
        message = ""
    End If
    Me.m_TraceSource.TraceEvent(severity, id, message)
End Sub

要以编程方式进行设置,您可以执行以下操作:

Dim listener As New FileLogTraceListener()
listener.Location = LogFileLocation.TempDirectory
listener.BaseFileName = "ConsoleApp_"
listener.Append = True
listener.Delimiter = "|"
listener.AutoFlush = True

一般情况下,您将在配置文件中配置它:

<system.diagnostics>
   <sources>
      <source name="TestSrc">
         <listeners>
               <add name="FileLogger" type="Microsoft.VisualBasic.Logging.FileLogTraceListener,
                           Microsoft.VisualBasic,Version=8.0.0.0,Culture=Neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
        </listeners>
     </source>
   </sources>
</system.diagnostics>

然后你可以像这样使用它:

Debug.Listeners.Add(listener)
Debug.WriteLine("Testing 1 2 3")