net core 3.1 logging 生成文件

_logger.LogInformation("你访问了首页");
            _logger.LogWarning("警告信息");
            _logger.LogError("错误信息");

使用DI 直接可以使用对象。

日志级别:Trace -》Debug-》 Information -》Warning-》 Error-》 Critical

级别包含范围由大到小 ,如 Trace 就包含了所有信息。

NLog 使用

 NLog 在 ASP.NET Core中的使用。

1.添加引用。

Install-Package NLog.Extensions.Logging -Pre

2.添加nlog.config 文件在项目里。

复制代码
<?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"
      autoReload="true"
      internalLogLevel="Warn"
      internalLogFile="internal-nlog.txt">

  <!-- define various log targets -->
  <targets>
    <!-- write logs to file -->
    <target xsi:type="File" name="allfile" fileName="nlog-all-${shortdate}.log"
                 layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />


    <target xsi:type="File" name="ownFile-web" fileName="nlog-own-${shortdate}.log"
             layout="${longdate}|${logger}|${uppercase:${level}}|  ${message} ${exception}" />

    <target xsi:type="Null" name="blackhole" />
  </targets>

  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />

    <!--Skip Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>
复制代码

3.在 Startup.cs -》 Configure

Host.CreateDefaultBuilder(args)
.ConfigureLogging((ILoggingBuilder logBuilder) =>
{
logBuilder.AddNLog();
logBuilder.AddConsole();
NLog.LogManager.LoadConfiguration("nlog.config");
})

运行程序,你就会发现,项目下多了两个文件,证明成功执行。

这里 nlog-all-*.log 是记录所有日志,nlog-own-*.log 记录跳过Microsoft 开头的类库输出的相关信息,剩下的信息。

4.发布(dotnet publish)注意事项

在 project.json 的  publishOptions节点 加入 nlog.config

复制代码
  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "appsettings.json",
      "web.config",
      "nlog.config"//加上nlog配置文件
    ]
  },
复制代码
原文地址:https://www.cnblogs.com/LiuFengH/p/13140708.html