我有一个NLog配置,对我的网络应用程序(ASP.NET Core)运行良好。 现在我尝试将NLog添加到我的webjobs中,但我无法弄清楚如何做到这一点。
在webjob项目中的Program.cs中,我需要以某种方式注入IHostingEnvironment和ILoggerFactory(我将两者都注入到Web应用程序的StartUp构造函数中)。 一旦我知道如何做到这一点,我应该能够完成配置。
如果不可能,我有什么替代方案?
我并不热衷于使用传递给webjob方法的TextWriter类,因为我想很难提取日志并将它们路由到我最终希望它去的地方。
答案 0 :(得分:0)
以下是在WebJob中使用NLog的步骤。
步骤1,为您的WebJob安装NLog.Config包。
Install-Package NLog.Config
步骤2,向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="logfile" xsi:type="File" fileName="file.txt" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logfile" />
</rules>
</nlog>
步骤3,使用LogManager类获取logger实例。
private static Logger logger = LogManager.GetLogger("MyLog");
步骤4,在获得记录器实例后,您可以使用以下代码编写日志。
logger.Trace("Sample trace message");
logger.Debug("Sample debug message");