简体   繁体   English

如何在asp.net core中通过Nlog将信息记录到一些单独的文件中?

[英]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.我们知道 Nlog 会将信息记录到两个文件中( nlog-all-*.txt / nlog-own-*.txt ,* 仅用于 DateTime)默认。

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.谢谢你。

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另见: https : //github.com/nlog/NLog/wiki/Filtering-log-messages

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM