Nlog的使用

ASP.NET Core 3

引用 

NLog.dll

NLog.Web.AspNetCore.dll

新建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="Info"
      internalLogFile="${basedir}/log/internal.log">

  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <!-- the targets to write to -->
  <targets>
    <target xsi:type="File" name="INFO-web" fileName="${basedir}/log/info${shortdate}.log"
           layout="${longdate}|${uppercase:${level}}|${message} |url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
    <target xsi:type="File" name="Error-web" fileName="${basedir}/log/error${shortdate}.log"
           layout="${longdate}|${uppercase:${level}}|${message} |url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
    <target xsi:type="File" name="allfile" fileName="${basedir}/log/all${shortdate}.log"
           layout="${longdate}|${uppercase:${level}}|${message} |url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
  </targets>

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

    <!--Skip non-critical Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" maxlevel="Info" final="true" />
    <logger name="*" minlevel="Info" writeTo="INFO-web" />
    <logger name="*" minlevel="Error" writeTo="Error-web" />
  </rules>
</nlog>

属性说明

配置元素

targets –定义日志目标/输出
rules –定义日志路由规则
extensions –从* .dll文件加载NLog扩展名
include–包括外部配置文件
variable –设置配置变量的值

目标

name –目标名称
type–目标类型–例如“文件”,“数据库”,“邮件”。使用名称空间时,此属性命名为xsi:type

日志级别(降序排列)

Fatal
Error
Warn 
Info
Debug 
Trace

规则

name –记录器名称过滤器-可能包含通配符(*和?)

minlevel –最低级别的日志

maxlevel –记录的最大级别

level –单级登录

levels -以逗号分隔的要记录级别的列表

writeTo –以逗号分隔的要写入的目标列表

final –最终规则匹配后未处理任何规则

enabled-设置为false禁用规则而不删除它

ruleName-规则标识符,允许使用Configuration.FindRuleByName和查找规则 Configuration.RemoveRuleByName

列:

<target xsi:type="File" name="INFO-web" fileName="${basedir}/log/${shortdate}.log"
           layout="${longdate}|${uppercase:${level}}|${message} |url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
${basedir}:项目路径/log/${shortdate}:日期.log
longdate:写入时间
message:记录的日志信息

更改Program

public static void Main(string[] args)
        {
            var logger = NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger();//配置Nlog文件
            try {
                logger.Debug("infoMain");
            }
            catch (Exception ex) {
                logger.Error(ex, "Stopped program because of exception");
            }
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .ConfigureLogging(logging=> {
                    logging.ClearProviders();
                    logging.SetMinimumLevel(LogLevel.Trace);
                }).UseNLog();//注入NLog
    }

控制器

public class HomeController : Controller
{
      private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            _logger.LogInformation("LogInformation");
            _logger.LogError("LogError");
            return View();
        }
}

日志文件位置:bin\Debug\netcoreapp3.1

谨以此用于记录,不足之处请多指教

参考文章

https://github.com/NLog/NLog/wiki/Configuration-file#configuration-file-locations

https://www.cnblogs.com/dflying/archive/2006/12/15/593158.html

posted @ 2020-12-18 15:04  尘雾  阅读(569)  评论(1编辑  收藏  举报