Melon NG
Melon NG

Reputation: 3004

How can I log information to a dividual file by Nlog?

I am about to log information of the Spider in some IActionResult to a dividual file with the date.

For example:
C:\20210317spider.txt
C:\20210318spider.txt
C:\20210319spider.txt

I don't want to use some method such as Logger.LogInformation to log all information into a file.

How can I achieve this? Thank you.

Upvotes: 0

Views: 63

Answers (1)

Rolf Kristensen
Rolf Kristensen

Reputation: 19912

You can use the ${shortdate} layoutrenderer inside the FileName-Layout for the NLog FileTarget:

<nlog>
  <targets>
    <target type="file" name="spiderFile" fileName="C:/${shortdate}spider.txt" />
  </targets>
  <rules>
    <logger name="Spider" writeTo="spiderFile" final="true" />
  </rules>
</nlog>

See also the NLog Tutorial and the list of available layoutrenders that can be used with NLog Layout.

Then you can do this with Microsoft ILoggerFactory:

public class MyClass
{
     private readonly ILogger _spiderLogger;

     public MyClass(ILoggerFactory loggerFactory)
     {
         _spiderLogger = loggerFactory.CreateLogger("Spider");
         _spiderLogger.LogInformation("Hello little spider");
     }
}

Upvotes: 1

Related Questions