我试图适应NLOG,发现很难为同一类的多个实例设置日志文件。每个类都在不同的线程上创建。请在下面的示例代码中找到:
{
ILogger mLogger;
public string Name { get; set; }
public string SecondName { get; set; }
private string mFilePath = @"C:\Logs\";
public test(string name, string secondname)
{
var target = new FileTarget(name) { FileName = mFilePath + name + ".txt" };
var config = new LoggingConfiguration();
config.AddRule(LogLevel.Info, LogLevel.Info, target);
LogManager.Configuration = config;
mLogger = LogManager.GetLogger(name);
LogManager.ReconfigExistingLoggers();
mLogger.Info("Hi from :" + name);
}
}
static void Main(string[] args)
{
new Thread(new ThreadStart(() => { new test("Stuart", "Broad"); })).Start();
new Thread(new ThreadStart(() =>
{
new test("John", "Smith");
})).Start();
new Thread(new ThreadStart(() =>
{
new test("Virat", "Kohli");
})).Start();
new Thread(new ThreadStart(() =>
{
new test("Christiano", "Ronaldo");
})).Start();
new Thread(new ThreadStart(() =>
{
new test("Pat", "cummins");
})).Start();
Console.Read();
}
输出为:2020-03-03 11:36:56.9404 | INFO |克里斯蒂亚诺| Hi from:克里斯蒂亚诺2020-03-03 11:36:56.9404 | INFO | Stuart | Hi来自:Stuart2020-03-03 11:36:56.9404 | INFO | John | Hi来自:John2020-03-03 11:36:56.9404 | INFO | Virat |您好:Virat2020-03-03 11:36:56.9404 | INFO |帕特|嗨::帕特
仅来自一个文件Christiano.txt
有人可以帮我配置这个吗?
谢谢。
LogManager.Configuration
是静态变量。分配时,会影响其他所有人。
而是为每个线程提供唯一的Logger。同一个FileTarget可以处理多个Logger。
{
ILogger mLogger;
public string Name { get; set; }
public string SecondName { get; set; }
public test(string name, string secondname)
{
mLogger = LogManager.GetLogger(name);
mLogger.Info("Hi from :" + name);
}
}
static void Main(string[] args)
{
string mFilePath = @"C:\Logs\";
var target = new FileTarget(name) { FileName = Path.Combine(mFilePath, "${logger}.txt") };
var config = new LoggingConfiguration();
config.AddRule(LogLevel.Info, LogLevel.Info, target);
LogManager.Configuration = config;
new Thread(new ThreadStart(() => { new test("Stuart", "Broad"); })).Start();
new Thread(new ThreadStart(() =>
{
new test("John", "Smith");
})).Start();
new Thread(new ThreadStart(() =>
{
new test("Virat", "Kohli");
})).Start();
new Thread(new ThreadStart(() =>
{
new test("Christiano", "Ronaldo");
})).Start();
new Thread(new ThreadStart(() =>
{
new test("Pat", "cummins");
})).Start();
Console.Read();
}
或者,您可以选择assign names to the threads,并使用NLog ${threadname}
代替FileName-Layout中的${logger}
。
还有另一种选择是使用NLog MappedDiagnosticsLogicalContext.SetScoped("TestName", name)创建范围,并在FileName-Layout中使用${mdlc:TestName}
。这还将使您可以将初始上下文传递给异步任务。