我有一个使用NLog的C#控制台应用程序。在那个应用程序中,我试图有条件地将信息记录到文件位置。作为一个人为的例子,让我们假设我有时需要将条目记录到" evens"日志文件,有时我需要将条目记录到"赔率"日志文件。为了做到这一点,我设置了以下配置:
<nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="evensLogFile" xsi:type="File" fileName="${basedir}/logs/evens.log" createDirs="true" keepFileOpen="true" encoding="utf-8" layout="${longdate} ${message}${exception:format=ToString}"></target>
<target name="oddsLogFile" xsi:type="File" fileName="${basedir}/logs/odds.log" createDirs="true" keepFileOpen="true" encoding="utf-8" layout="${longdate} ${message}${exception:format=ToString}"></target>
</targets>
<rules>
<logger name="Evens" minlevel="Trace" writeTo="evensLogFile" />
<logger name="Odds" minlevel="Trace" writeTo="oddsLogFile" />
</rules>
</nlog>
现在,在我的代码中,当我想写一个日志条目时,我有以下内容:
public void Log(string message)
{
var random = new Random();
var i = random.Next(1, 11);
Logger logger = null;
if(i%2 == 0) {
// somehow get a logger for "evens"
} else {
// somehow get a logger for "odds"
}
logger.Log(LogLevel.Info, message);
}
如果我使用Logger logger = LogManager.GetCurrentClassLogger();
,我可以成功地将日志写入单个日志文件但是,我无法根据某些逻辑弄清楚如何将不同的日志消息记录到不同的文件中。任何帮助表示赞赏!
答案 0 :(得分:3)
我用谷歌搜索了“NLog多个文件目标”和this is what I came across。以下代码应与您当前的配置一起使用。
class Program
{
static void Main(string[] args)
{
Log("message 1");
Log("message 2");
Log("message 3");
Log("message 4");
}
public static void Log(string message)
{
var random = new Random();
var i = random.Next(1, 11);
Logger logger = null;
if (i % 2 == 0)
{
logger = LogManager.GetLogger("Evens");
}
else
{
logger = LogManager.GetLogger("Odds");
}
logger.Trace($"{message} - {i}");
}
}
<强> nlog.config 强>
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="evensLogFile" xsi:type="File" fileName="${basedir}/logs/evens.log" createDirs="true" keepFileOpen="true" encoding="utf-8" layout="${longdate} ${message}${exception:format=ToString}"></target>
<target name="oddsLogFile" xsi:type="File" fileName="${basedir}/logs/odds.log" createDirs="true" keepFileOpen="true" encoding="utf-8" layout="${longdate} ${message}${exception:format=ToString}"></target>
</targets>
<rules>
<logger name="Evens" minlevel="Trace" writeTo="evensLogFile" />
<logger name="Odds" minlevel="Trace" writeTo="oddsLogFile" />
</rules>
</nlog>
<强> odds.log 强>
2018-04-24 19:50:04.9421留言2 - 3
2018-04-24 19:50:05.1211消息3 - 9
<强> evens.log 强>
2018-04-24 19:50:04.7572留言1 - 8
2018-04-24 19:50:05.3137留言4 - 6
编辑使用目标而不是记录器名称。 Edit2:添加了program.cs,nlog.config,输出日志
答案 1 :(得分:2)
您可以按名称获取日志,例如:
if(i%2 == 0) {
logger = LogManager.GetLogger("Evens");
} else {
logger = LogManager.GetLogger("Odds");
}