Melon NG
Melon NG

Reputation: 3004

How can I log information into some dividual files by Nlog in asp.net core?

As we know Nlog will log the information into two files(nlog-all-*.txt/nlog-own-*.txt,* is just for the DateTime) for default.

Well, now I want to log the information into different files. For example:

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();
        }  

How can I achieve this? Thank you.

Upvotes: 1

Views: 52

Answers (1)

Rolf Kristensen
Rolf Kristensen

Reputation: 19912

Maybe something like this:

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();
        }
}

Then you can do something like this:

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

See also: https://github.com/nlog/NLog/wiki/Filtering-log-messages

Upvotes: 1

Related Questions