2012-01-26 27 views
2

我想注入一個類型的信息到日誌呼叫只有一個呼叫,像我如何注入屬性在log4net的

public sealed class Logger 
{ 
    private readonly log4net.ILog _logger; 

    public Logger() 
    { 
     // somehow assing this._logger ... doesn't matter actually 
    } 

    public void Info<T>(string message) 
    { 
     if (!this._logger.IsInfoEnabled) 
     { 
      return; 
     } 

     var typeOfT = typeof (T); 
     var typeName = typeOfT.FullName; 

     // how to set a property here, only for this one single call 
     // which i can reference in the config 

     this._logger.Info(message); 
    } 
} 

註釋清楚:在某些時候,我想只爲這個特定的調用注入我的泛型參數的FullName

我使用log4net的1.2.11.0

回答

4

其實這是很簡單的:

public class Foo : log4net.Core.LogImpl 
{ 
    private static readonly Type DeclaringType = typeof (Foo); 

    public Foo(log4net.Core.ILoggerWrapper loggerWrapper) 
     : this(loggerWrapper.Logger) {} 

    public Foo(log4net.Core.ILogger logger) 
     : base(logger) {} 

    protected LoggingEvent GetLoggingEvent<T>(Level level, string message, Exception exception = null) 
    { 
     var loggingEvent = new LoggingEvent(DeclaringType, this.Logger.Repository, this.Logger.Name, level, message, exception); 
     loggingEvent.Properties["type"] = typeof (T).FullName; 

     return loggingEvent; 
    } 

    public void Info<T>(string message) 
    { 
     if (!this.IsInfoEnabled) 
     { 
      return; 
     } 

     var loggingEvent = this.GetLoggingEvent<T>(Level.Info, message); 

     this.Logger.Log(loggingEvent); 
    } 

    public void Info<T>(string message, params object[] args) 
    { 
     if (!this.IsInfoEnabled) 
     { 
      return; 
     } 

     message = string.Format(message, args); 

     var loggingEvent = this.GetLoggingEvent<T>(Level.Info, message); 

     this.Logger.Log(loggingEvent); 
    } 
}