1

I've got an NLog configuration which works just fine for my web app (ASP.NET Core). Now I'm trying to add NLog to my webjobs, but I can't figure out how to do it.

In Program.cs within the webjob project, I need to somehow inject IHostingEnvironment and ILoggerFactory (Both of which I inject into the StartUp constructor of the web app). Once I know how to do that, I should be able to finish off the configuration.

If that's not possible, what alternatives do I have?

I'm not keen to use the TextWriter class passed into the webjob methods, as I imagine it would be difficult to extract the logs and route them to where I ultimately want it to go.

Steviebob
  • 1,705
  • 2
  • 23
  • 36

1 Answers1

0

Following are steps of using NLog in WebJob.

Step 1, install NLog.Config package for your WebJob.

Install-Package NLog.Config

Step 2, add rules and targets to NLog.config files. Following is the sample of writing logs to a file.

<?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>

Step 3, get logger instance using LogManager class.

private static Logger logger = LogManager.GetLogger("MyLog");

Step 4, after got the logger instance, you could write log using following code.

logger.Trace("Sample trace message");
logger.Debug("Sample debug message");
Amor
  • 8,325
  • 2
  • 19
  • 21