zoukankan      html  css  js  c++  java
  • Asp.Net Core基础NLog记录日志

    Asp.Net Core自带内建日志,同时也允许开发人员轻松切换到其他日志框架。下面将在实战项目中使用NLog记录日志。

    1.首先创建Asp.Net Core Web项目

    2.在项目中添加NLog相应包

      

    Install-Package NLog.Web.AspNetCore -Version 4.8.0

    3.在项目中添加NLog配置文件

    Install-Package NLog.Config

    NLog.config添加至项目中后,在VS中右击文件,查看属性,并将文件属性设置为始终复制或者更新时复制

    4.编辑NLog.config文件

    双击文件,进入编辑,根据需要修改内容。

    配置文件主要包括两个部分:输出目标target路由规则rule。

    4.1输出目标target

    每个target代表一个输出目标,它主要包含两个属性:name和type。name是输出模板的名称,在后面的路由规则中使用,type则是输出类型,常见的有

    • Console        输出到控制台
    • Debugger     输出到
    • File        输出到文件
    • Mail        输出为邮件发送
    • Network        输出到网络地址
    • Database        输出到数据库

    当选择某一种类型的时候,还需要配置相应的参数。如输出类型是File时,我们要配置日志路径filename,这里是可以使用一些变量的(花括号里面的部分),举例:

        fileName="${basedir}/Logs/Error/${shortdate}/error.txt"

    输出的日志格式为 /Log/2014-10-01/err.txt    每天生成一个文件夹,非常方便。

    输出格式的控制:

    有的时候,我们需要对时间、异常等这些对象的输出格式进行控制。它们可以通过修改layout参数来实现。这一部分是相对比较复杂的,具体配置参数请到官网查看。

    4.2路由规则rule

    路由规则主要用于将日志和输出目标匹配起来,它一般有如下几个属性

    • name - 记录者的名字 (允许使用通配符*)
    • minlevel - 匹配日志范围的最低级别
    • maxlevel - 匹配日志范围的最高级别
    • level - 匹配的单一日志级别
    • levels - 匹配的一系列日志级别,由逗号分隔。
    • writeTo - 规则匹配时日志应该被写入的一系列目标,由逗号分隔。

    看上去有好几个属性,实际上用起来还是比较简单的,比如:

        <logger name="*" writeTo="console" />    将所有的日志输出到控制台中
        <logger name="*" minlevel="Debug" writeTo="debugger" />            将Debug级别以上的日志输出到Debugger中
        <logger name="*" minlevel="Error" writeTo="error_file" />        将Error级别以上的日志输出到文件中

    另外,NLOG支持配置多个路由规则,可以非常方便我们的输出。

    具体详情请看官网参数说明:https://github.com/nlog/NLog/wiki/Configuration-file#configuration-file-locations

    下面是我的配置文件:

    <?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"
          xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
          autoReload="true"
          throwExceptions="false"
          internalLogLevel="Off" internalLogFile="c:	emp
    log-internal.log">
    
      <!-- optional, add some variables
      https://github.com/nlog/NLog/wiki/Configuration-file#variables
      -->
      <variable name="myvar" value="myvalue"/>
    
      <!--
      See https://github.com/nlog/nlog/wiki/Configuration-file
      for information on customizing logging rules and outputs.
       -->
      <targets>
    
        <!-- write logs to file  -->
        <target xsi:type="File" name="allfile" fileName="c:	emp
    log-all-${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
    
        <!-- another file log, only own logs. Uses some ASP.NET core renderers -->
        <target xsi:type="File" name="ownFile-web" fileName="c:	emp
    log-own-${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
    
        <!--
        add your targets here
        See https://github.com/nlog/NLog/wiki/Targets for possible targets.
        See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
        -->
    
        <!--
        Write events to a file with the date in the filename.
        <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
                layout="${longdate} ${uppercase:${level}} ${message}" />
        -->
      </targets>
    
      <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" />
        <!-- BlackHole without writeTo -->
        <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
    
    
        <!--
        Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
        <logger name="*" minlevel="Debug" writeTo="f" />
        -->
      </rules>
    </nlog>

    5.在startup.cs中注入日志

    public Startup(IConfiguration configuration, IHostingEnvironment env)
    {
         env.ConfigureNLog("NLog.config");
         Configuration = configuration;
    }
    
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
          //...
                
          //add NLog to ASP.NET Core
          loggerFactory.AddNLog();
                
          //...
    
    }

    运行项目后,产生日志记录

     6.全局异常处理

    添加过滤器;并在Startup.cs文件的ConfigureServices方法中添加过滤器

    public class GlobalExceptionFilter: IExceptionFilter
        {
           public static Logger logger = LogManager.GetCurrentClassLogger();
    
            public void OnException(ExceptionContext filterContext)
            {
                logger.Error(filterContext.Exception);
                var result = new BaseResult()
                {
                    ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode,//系统异常代码
                    ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg,//系统异常信息
                };
                filterContext.Result = new ObjectResult(result);
                filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                filterContext.ExceptionHandled = true;
            }
        }
  • 相关阅读:
    2017年5月19日13:58:17 问题记录
    2017年5月17日20:14:29 rabbitmq 消费 异常信息无法处理 导致轮询
    2017年5月12日15:10:46 rabbitmq不支持非阻塞调用服务器
    2017年5月11日17:43:06 rabbitmq 消费者队列
    2017年5月10日16:11:28 定义所有问题
    MyBatis Plus 只插入只有自增id字段的表
    Centos 7 关闭报警音
    关于git项目切换远程提交路径和提交仓库
    IDEA通过git回滚到某个提交节点或某个版本
    IDEA使用@Autowired注解报错解决方案
  • 原文地址:https://www.cnblogs.com/charles-jiang/p/10397582.html
Copyright © 2011-2022 走看看