我有以下课程:
private string name;
private Logger logger;
private LogLevel lvl;
private LoggingConfiguration config;
public Logger(string name, string path, string format, LogLevel lvl)
{
this.name = name;
FileTarget fileTarget = new FileTarget();
fileTarget.FileName = path;
fileTarget.Layout = format;
this.lvl = lvl;
LoggingRule rule = new LoggingRule(name, lvl, fileTarget);
config = new LoggingConfiguration();
config.AddTarget(name, fileTarget);
config.LoggingRules.Add(rule);
LogManager.Configuration = config;
logger = LogManager.GetLogger(this.name);
logger.Trace("test");
}
我创建了两个不同的记录器:
Logger("log1", "c:\\test\\log1.txt", ${message}, LogLevel.Debug);
Logger("log2", "c:\\test\\log2.txt", ${message}, LogLevel.Debug);
这两个文件都是使用字符串test创建的。但是当我尝试使用(类方法)记录消息时:
public void Log(string msg)
{
logger = NLog.LogManager.GetLogger(name);
//LogManager.Configuration = config;
//LogManager.Configuration.Reload();
logger.Log(lvl, msg);
}
该消息仅记录在第二个文件中。我做错了什么?
答案 0 :(得分:2)
我不太确定,但据我记得LogManager.Configuration
有点全局,并且用于此后创建的所有记录器。因此,对Logger()
函数的第二次调用将覆盖您在第一次调用期间所做的配置设置。这就是为什么日志记录只发生在后面的文件中。
要解决此问题,您必须首先为它们创建文件目标和规则,然后将目标和规则添加到日志记录配置中。
所以基本方法(没有单独的功能)应该看起来像这样:(注意:代码尚未经过测试,所以复制和粘贴风险自负!)
FileTarget fileTarget1 = new FileTarget();
fileTarget1.FileName = "C:\\foo\\bar1.txt";
fileTarget1.Layout = "${message}";
FileTarget fileTarget2 = new FileTarget();
fileTarget2.FileName = "C:\\foo\\bar2.txt";
fileTarget2.Layout = "${message}";
LoggingRule rule1 = new LoggingRule("log1", LogLevel.Debug, fileTarget1);
LoggingRule rule2 = new LoggingRule("log2", LogLevel.Debug, fileTarget2);
config = new LoggingConfiguration();
config.AddTarget("log1", fileTarget1);
config.LoggingRules.Add(rule1);
config.AddTarget("log2", fileTarget2);
config.LoggingRules.Add(rule2);
LogManager.Configuration = config;
logger = LogManager.GetLogger(this.name);
logger.Trace("test");
我将详细介绍如何将其作为某种可重复使用的功能/方法作为读者练习。 ;)
答案 1 :(得分:1)
另外,
您可以创建两个日志记录规则,但另一个选项是使用1 LoggingRule
,并使文件路径依赖于loggername。
e.g。
FileTarget fileTarget = new FileTarget();
fileTarget.FileName = "${basedir}/${logger}.log";
fileTarget.Layout = "${message}";
LoggingRule rule1 = new LoggingRule("*", LogLevel.Debug, fileTarget);
var config = new LoggingConfiguration();
config.AddTarget("log1", fileTarget);
config.LoggingRules.Add(rule1);
LogManager.Configuration = config;
var logger1 = LogManager.GetLogger("logger1");
logger.Trace("im logger1 to logger1.log");
var logger2 = LogManager.GetLogger("logger2");
logger.Trace("im logger2 and going to logger2.log");