我如何通过 asp.net 核心中的 Nlog 将信息记录到一些单独的文件中?
How can I log information into some dividual files by Nlog in asp.net core?
据我们所知,Nlog默认会将信息记录到两个文件中(nlog-all-*.txt
/nlog-own-*.txt
,*仅针对DateTime)。
好吧,现在我想把信息记录到不同的文件中。例如:
public IActionResult First()
{
///to log the information into C:/nlog-First-*.txt
return View();
}
public IActionResult Second()
{
///to log the information into C:/nlog-Second-*.txt
return View();
}
我怎样才能做到这一点?谢谢。
也许是这样的:
class MyClass
{
ILogger _firstLogger;
ILogger _secondLogger;
public MyClass(ILoggerFactory factory)
{
_firstLogger = factory.CreateLogger($"{GetType().ToString()}.ActionResult.First");
_secondLogger = factory.CreateLogger($"{GetType().ToString()}.ActionResult.Second");
}
public IActionResult First()
{
///to log the information into C:/nlog-First-*.txt
_firstLogger.LogInformation("Hello First");
return View();
}
public IActionResult Second()
{
///to log the information into C:/nlog-Second-*.txt
_firstLogger.LogInformation("Hello Second");
return View();
}
}
那么你可以这样做:
<nlog>
<targets>
<target type="file" name="actionResultFile" fileName="nlog-${logger:shortName=true}-${shortdate}.txt" />
</targets>
<rules>
<logger name="*.ActionResult.*" minlevel="Trace" writeTo="actionResultFile" />
</rules>
</nlog>
另请参阅:https://github.com/nlog/NLog/wiki/Filtering-log-messages
据我们所知,Nlog默认会将信息记录到两个文件中(nlog-all-*.txt
/nlog-own-*.txt
,*仅针对DateTime)。
好吧,现在我想把信息记录到不同的文件中。例如:
public IActionResult First()
{
///to log the information into C:/nlog-First-*.txt
return View();
}
public IActionResult Second()
{
///to log the information into C:/nlog-Second-*.txt
return View();
}
我怎样才能做到这一点?谢谢。
也许是这样的:
class MyClass
{
ILogger _firstLogger;
ILogger _secondLogger;
public MyClass(ILoggerFactory factory)
{
_firstLogger = factory.CreateLogger($"{GetType().ToString()}.ActionResult.First");
_secondLogger = factory.CreateLogger($"{GetType().ToString()}.ActionResult.Second");
}
public IActionResult First()
{
///to log the information into C:/nlog-First-*.txt
_firstLogger.LogInformation("Hello First");
return View();
}
public IActionResult Second()
{
///to log the information into C:/nlog-Second-*.txt
_firstLogger.LogInformation("Hello Second");
return View();
}
}
那么你可以这样做:
<nlog>
<targets>
<target type="file" name="actionResultFile" fileName="nlog-${logger:shortName=true}-${shortdate}.txt" />
</targets>
<rules>
<logger name="*.ActionResult.*" minlevel="Trace" writeTo="actionResultFile" />
</rules>
</nlog>
另请参阅:https://github.com/nlog/NLog/wiki/Filtering-log-messages