关于使用 StructureMap 动态创建记录器,这就是我前一段时间所做的。(注意“注入”,我接下来解释)
namespace EC2Utilities.Common.Factory
{
public static class ContainerBootstrapper
{
public static void BootstrapStructureMap()
{
// Initialize the static ObjectFactory container
ObjectFactory.Initialize(x =>
{
x.For<IBackupEngine>().Use<BackupEngine>();
x.For<IConfigResourceAccess>().Use<ConfigResourceAccess>();
x.For<IEc2ResourceAccess>().Use<Ec2ResourceAccess>();
x.For<IScheduleEngine>().Use<ScheduleEngine>();
x.For<IScheduleManager>().Use<ScheduleManager>();
x.For<IBackupManager>().Use<BackupManager>();
x.For<ILog>().Use(y => LogManager.GetLogger("Injected"));
x.For<IInstanceManager>().Use<InstanceManager>();
x.RegisterInterceptor(new ResourceAccessTypeInterceptor());
});
}
}
}
关于保持在 appender.layout.conversionPattern 中使用 %C.%M 来获取您的类和名称的好处,诀窍是将 ILog 方法公开为包装器中的委托,因此调用类实际上是在ILog 而不是你的包装器:
namespace LoggingTest
{
public delegate void LogFormat(string format, params object[] args);
public interface ILoggerWrapper
{
Action<object> Debug { get; }
Action<object, Exception> DebugEx { get; }
LogFormat DebugFormat { get; }
Action<object> Info { get; }
Action<object, Exception> InfoEx { get; }
LogFormat InfoFormat { get; }
Action<object> Warn { get; }
Action<object, Exception> WarnEx { get; }
LogFormat WarnFormat { get; }
Action<object> Error { get; }
Action<object, Exception> ErrorEx { get; }
LogFormat ErrorFormat { get; }
Action<object> Fatal { get; }
Action<object, Exception> FatalEx { get; }
LogFormat FatalFormat { get; }
}
}
和实施:
namespace LoggingTest
{
public class LoggerWrapper : ILoggerWrapper
{
private readonly ILog _log;
public LoggerWrapper(ILog log)
{
_log = log;
}
public Action<object> Debug { get { return _log.Debug; } }
public Action<object, Exception> DebugEx { get { return _log.Debug; } }
public LogFormat DebugFormat { get { return _log.DebugFormat; } }
public Action<object> Info { get { return _log.Info; } }
public Action<object, Exception> InfoEx { get { return _log.Info; } }
public LogFormat InfoFormat { get { return _log.InfoFormat; } }
public Action<object> Warn { get { return _log.Warn; } }
public Action<object, Exception> WarnEx { get { return _log.Warn; } }
public LogFormat WarnFormat { get { return _log.WarnFormat; } }
public Action<object> Error { get { return _log.Error; } }
public Action<object, Exception> ErrorEx { get { return _log.Error; } }
public LogFormat ErrorFormat { get { return _log.ErrorFormat; } }
public Action<object> Fatal { get { return _log.Fatal; } }
public Action<object, Exception> FatalEx { get { return _log.Fatal; } }
public LogFormat FatalFormat { get { return _log.FatalFormat; } }
}
}
您当然还需要在容器中注册 ILoggerWrapper。
HTH,埃里克