【问题标题】:How can I log information into some dividual files by Nlog in asp.net core?如何在 asp.net core 中通过 Nlog 将信息记录到一些单独的文件中?
【发布时间】:2019-12-15 09:09:55
【问题描述】:

我们知道 Nlog 默认会将信息记录到两个文件中(nlog-all-*.txt/nlog-own-*.txt,* 仅用于日期时间)。

好吧,现在我想将信息记录到不同的文件中。例如:

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

我怎样才能做到这一点?谢谢。

【问题讨论】:

    标签: c# asp.net-core .net-core nlog


    【解决方案1】:

    可能是这样的:

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

    然后你可以这样做:

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

    另请参阅:https://github.com/nlog/NLog/wiki/Filtering-log-messages

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-09
      • 2019-02-28
      • 2021-11-27
      • 2017-11-26
      • 1970-01-01
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多