如何使用PostSharp方面的自定义事件侦听器

时间:2014-09-29 11:24:24

标签: logging event-listener postsharp

我有一个AutoLogExceptionAspect类及其合作事件源AutoLogExceptionEventSource,如下所示:

<Serializable()>
Public Class AutoLogExceptionAspect
    Inherits OnExceptionAspect
    Public Overrides Sub OnException(ByVal args As MethodExecutionArgs)
        AutoLogExceptionEventSource.Log.LogException(args.Exception.GetType().Name, args.Exception.Message, args.Exception.StackTrace)
        args.FlowBehavior = FlowBehavior.Continue
    End Sub
End Class

<EventSource(Name:=EventSourceNames.AutoLogException)>
Public NotInheritable Class AutoLogExceptionEventSource
    Inherits EventSource
    Public Class Tasks
        Public Const MethodExecution As EventTask = CType(1, EventTask)
    End Class
    Private Const ExceptionLog As Integer = EventIdBases.AutoLogException + 1
    Private Const MethodExecution As Integer = CType(1, EventTask)
    Private Shared ReadOnly Instance As Lazy(Of AutoLogExceptionEventSource) = New Lazy(Of AutoLogExceptionEventSource)(Function() New AutoLogExceptionEventSource())
    Public Shared ReadOnly Property Log As AutoLogExceptionEventSource
        Get
            Return Instance.Value
        End Get
    End Property
    <[Event](ExceptionLog, Level:=EventLevel.Error, Task:=MethodExecution, Opcode:=EventOpcode.Info)>
    Public Sub LogException(exceptionType As String, message As String, stackTrace As String)
        If (IsEnabled()) Then
            WriteEvent(ExceptionLog, exceptionType, message, stackTrace)
        End If
    End Sub
End Class

我还有RollingLogFileTraceListener TraceListener 派生自FileLogTraceListener,在ctor中有一些cusatom设置。现在我不知道如何将这个监听器连接到我的EventSource类。我不想用大异常粘贴痕迹填充我的Windows事件日志。如何将此RollingLogFileTraceListenerAutoLogExceptionEventSource一起使用?

1 个答案:

答案 0 :(得分:0)

AutoLogExceptionAspect中,您需要使用自定义TraceSource而不是EventSource。然后,您可以在配置文件中或直接在代码中配置与此TraceSource关联的侦听器。您可以在MSDN上找到一些示例 - How to: Create and Initialize Trace Sources