我想在日志调用中注入一个类型信息,比如
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
答案 0 :(得分:5)
实际上这很简单:
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);
}
}