Log4net - 如何在WCF中记录调用方法名称

时间:2013-07-31 10:49:23

标签: singleton log4net wrapper

我为log4net编写了一个Singleton包装器,它将在我的WCF服务的所有层中调用。我无法记录调用方法名称。请提示以下代码中是否有任何输入。感谢。

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Imports log4net
Imports System.Reflection

Public Class Logger
Implements ILog

Private Shared m_instance As Logger
Private Shared log As log4net.ILog = Nothing

Public Sub New()
    If log Is Nothing Then
        'log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType) ' -> This always logs 'Logger'
        log = log4net.LogManager.GetLogger(Assembly.GetCallingAssembly(), "MyLogger")  ' -> This always logs 'MyLogger'
    End If

End Sub

Public Shared ReadOnly Property Write() As Logger
    Get
        m_instance = New Logger()
        Return m_instance
    End Get
End Property

Public Sub Debug(msg As String) Implements ILog.Debug
    log.Debug(msg)
End Sub

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''  

Public Interface ILog
     Sub Debug(msg As String)
End Interface
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

我已经使其更简单,如下所示记录方法名称。但我必须将classname作为参数传递。请问这是可以接受的设计吗?

''''' Calling code ''''''''''''''''''''
Logger(of MyClassName).Debug("message")


''''''Log4net wrapper'''''''''''''''''''''
Imports log4net
Imports System.Reflection

Public NotInheritable Class Logger(Of T)

Private Shared log As log4net.ILog = Nothing

Private Shared ReadOnly Property LogProvider() As log4net.ILog
    Get
        If (log Is Nothing) Then
            Dim CallingMethod As String = GetType(T).ToString() & "." & (New StackTrace()).GetFrame(2).GetMethod().Name
            log = log4net.LogManager.GetLogger(CallingMethod)
        End If
        Return log
    End Get
End Property

Public Shared Sub Debug(msg As String)
    LogProvider.Debug(msg)
End Sub

1 个答案:

答案 0 :(得分:1)

日志记录实例只能有一个名称,您无法更改它。如果要在每个方法中使用不同的名称,则需要为ech方法创建记录器。

    log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType) ' -> This always logs 'Logger'
    log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().Name) ' -> This gives you the name of the current method
    log = log4net.LogManager.GetLogger(Assembly.GetCallingAssembly(), "MyLogger")  ' -> This always logs 'MyLogger'

在方法中创建记录器,如:

    ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().Name) ' -> This gives you the name of the current method

你将拥有一个带有方法名称的记录器,我会添加该类的名称:

    ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType + "." + MethodBase.GetCurrentMethod().Name) ' -> This gives you the name of the current method