我需要动态创建记录器,所以使用帖子from here和反射器的帮助我已经设法动态创建记录器,但我想知道我是否应该担心别的......我不知道具有什么影响可以做到。
public static ILog GetDyamicLogger(Guid applicationId)
{
Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
RollingFileAppender roller = new RollingFileAppender();
roller.LockingModel = new log4net.Appender.FileAppender.MinimalLock();
roller.AppendToFile = true;
roller.RollingStyle = RollingFileAppender.RollingMode.Composite;
roller.MaxSizeRollBackups = 14;
roller.MaximumFileSize = "15000KB";
roller.DatePattern = "yyyyMMdd";
roller.Layout = new log4net.Layout.PatternLayout();
roller.File = "App_Data\\Logs\\"+applicationId.ToString()+"\\debug.log";
roller.StaticLogFileName = true;
PatternLayout patternLayout = new PatternLayout();
patternLayout.ConversionPattern = "%date [%thread] %-5level %logger [%property{NDC}] - %message%newline";
patternLayout.ActivateOptions();
roller.Layout = patternLayout;
roller.ActivateOptions();
hierarchy.Root.AddAppender(roller);
hierarchy.Root.Level = Level.All;
hierarchy.Configured = true;
DummyLogger dummyILogger = new DummyLogger(applicationId.ToString());
dummyILogger.Hierarchy = hierarchy;
dummyILogger.Level = log4net.Core.Level.All;
dummyILogger.AddAppender(roller);
return new LogImpl(dummyILogger);
}
internal sealed class DummyLogger : Logger
{
// Methods
internal DummyLogger(string name)
: base(name)
{
}
}
干杯。
答案 0 :(得分:2)
我想说你不必担心在代码中创建记录器。这是创建它们的受支持方法之一。在应用程序运行时,您确实无法更改内容(除非您为其编写代码)。这只是使用配置文件的好处之一。
答案 1 :(得分:0)
我注意到的一件事是,以这种方式创建的记录器未“正确地”输入到日志层次结构中(LogManager.GetLogger
不会返回它)。但是,如果我这样使用 dummyILogger.Hierarchy = hierarchy;
而不是hierarchy.GetLogger(string ILoggerFactory)
,那么它可以解决此问题:
//End of the GetDyamicLogger function
hierarchy.GetLogger(loggerName, new DynamicLoggerFactory(loggerName, dummyILogger));
return new LogImpl(dummyILogger);
}
/// <summary>
/// Dummy <c>ILoggerFactory</c> implementation used by <c>Hierarchy.GetLogger</c>.
/// </summary>
internal sealed class DynamicLoggerFactory : ILoggerFactory
{
private readonly string name;
private readonly Logger logger;
public DynamicLoggerFactory(string name, Logger logger) { this.name=name; this.logger=logger; }
public Logger CreateLogger(log4net.Repository.ILoggerRepository repository, string name)
{
if(name != this.name) { throw new ArgumentOutOfRangeException("name", name, "Unexpected logger name queried."); }
return this.logger;
}
}
有了这个,LogManager.GetLogger
将返回动态创建的记录器。