【发布时间】:2018-02-02 11:05:37
【问题描述】:
我的主类正在运行 10 个并发线程,我希望将每个线程的输出放在一个单独的文件中。我想将一些线程分组在同一个文件中。为此,我编写了以下类,它会即时生成LoggingConfiguration。我想生成不同的Logger 对象,每个对象都有自己特定的LoggingConfiguration。
下面是我的配置生成方法:
private LoggingConfiguration GetLoggerConfig(string target)
{
if (!Directory.Exists(target)){
Directory.CreateDirectory(target);
}
// Step 1. Create configuration object
var config = new LoggingConfiguration();
// Step 2. Create targets and add them to the configuration
var consoleTarget = new ColoredConsoleTarget();
config.AddTarget("console", consoleTarget);
var fileTarget = new FileTarget();
config.AddTarget("file", fileTarget);
var asyncWrapper = new AsyncTargetWrapper();
asyncWrapper.QueueLimit = 5000;
asyncWrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Grow;
asyncWrapper.WrappedTarget = fileTarget;
// Step 3. Set target properties
consoleTarget.Layout = @"${longdate} | ${logger} | ${level} | ${message}";//@"${date:format=HH\:mm\:ss} ${logger} ${message}";
fileTarget.FileName = Path.Combine(target, "logs-${shortdate}.txt");
fileTarget.Layout = "${longdate} | ${machinename} | ${processid} | ${processname} | ${logger} | ${level} | ${message}";
// Step 4. Define rules
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget));
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, asyncWrapper));
return config;
}
我正试图达到我的语法看起来像这样的地步:
Logger logger1 = GetLoggerConfig(@"C:\Target1");
Logger logger2 = GetLoggerConfig(@"C:\Target2");
logger1.Info("hello -- should be printed in a file");
logger2.Info("World -- should be printed in a different file");
我所拥有的是:在每个线程中我调用LogManager.Configuration = GetLoggerConfig(@"C:\Target1");,然后来自先前启动线程的所有日志都出现在那里。
我不知道在运行前我有多少不同的目标。
【问题讨论】: