我正在使用log4net在.NET Compact Framework上的应用程序中进行程序记录,这很好。
但是,我需要每隔几秒就将数据输出到一个文本文件,并且想知道我是否可以使用log4net。问题是,每次我指定一个新的appender时,我的所有程序记录都会附加到它上面。
因此,要重新迭代,我需要两个appender。一个是全局的并处理我的所有程序日志记录,另一个是附加到类中的私有成员记录器以输出数据的appender。我不希望任何日志出现在两个appender中。
这可能吗?我必须在代码中指定我的log4net配置,因为紧凑框架不支持配置文件。我当前的appender定义如下:
Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
hierarchy.Root.RemoveAllAppenders(); //Remove any other appenders
RollingFileAppender fileAppender = new RollingFileAppender();
fileAppender.MaxFileSize = 10000000; //10MB in bytes
fileAppender.MaxSizeRollBackups = 10;
fileAppender.RollingStyle = RollingFileAppender.RollingMode.Size;
fileAppender.AppendToFile = true;
fileAppender.LockingModel = new FileAppender.MinimalLock();
fileAppender.File = @"C:\ProgramLog.txt";
log4net.Filter.LevelRangeFilter filter = new log4net.Filter.LevelRangeFilter();
filter.LevelMin = log4net.Core.Level.Warn;
filter.LevelMax = log4net.Core.Level.Fatal;
fileAppender.AddFilter(filter);
PatternLayout pl = new PatternLayout();
pl.ConversionPattern = "%utcdate [%thread] %-5level %logger - %message%newline";
pl.ActivateOptions();
fileAppender.Layout = pl;
fileAppender.ActivateOptions();
log4net.Config.BasicConfigurator.Configure(fileAppender);
答案 0 :(得分:2)
我找到了一种使用存储库执行此操作的方法。我编写了一个类来封装所有的log4net配置:
public class CustomLogger
{
private readonly ILog log;
public CustomLogger(string name)
{
var repository = LogManager.CreateRepository(name);
Hierarchy hierarchy = (Hierarchy)repository;
hierarchy.Root.RemoveAllAppenders(); //Remove any other appenders
RollingFileAppender fileAppender = new RollingFileAppender();
fileAppender.MaxFileSize = 10000000; //10MB in bytes
fileAppender.MaxSizeRollBackups = 10;
fileAppender.RollingStyle = RollingFileAppender.RollingMode.Size;
fileAppender.AppendToFile = true;
fileAppender.LockingModel = new FileAppender.MinimalLock();
fileAppender.File = @"C:\" + name + "_LOG.txt";
PatternLayout pl = new PatternLayout();
pl.ConversionPattern = "%utcdate,%message%newline";
pl.ActivateOptions();
fileAppender.Layout = pl;
fileAppender.ActivateOptions();
log4net.Config.BasicConfigurator.Configure(repository, fileAppender);
this.log = LogManager.GetLogger(name, name);
}
public void Log(string message)
{
this.log.Info(message);
}
}
用法:
var logger1 = new CustomLogger("1111111");
var logger2 = new CustomLogger("2222222");
var logger3 = new CustomLogger("3333333");
logger1.Log("Test1");
logger2.Log("Test2");
logger3.Log("Test3");