分类目录

链接

2019 年 12 月
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

近期文章

热门标签

新人福利,免费薅羊毛

现在位置:    首页 > .NET > 正文
.NET Core使用Nlog记录日志
.NET 暂无评论 阅读(268)

1.引入Nuget包

Nlog

Nlog.Web.AspNetCore

2.添加nlog配置文件

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <nlogxmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. autoReload="true"
  5. internalLogLevel="Warn"
  6. internalLogFile="internal-nlog.txt">
  7. <!--define various log targets-->
  8. <targets>
  9. <!--write logs to file-->
  10. <targetxsi:type="File"name="allfile"fileName="nlog-all-${shortdate}.log"
  11. layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}"/>
  12. <targetxsi:type="File"name="ownFile-web"fileName="nlog-my-${shortdate}.log"
  13. layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}"/>
  14. <targetxsi:type="Null"name="blackhole"/>
  15. </targets>
  16. <rules>
  17. <!--All logs, including from Microsoft-->
  18. <loggername="*"minlevel="Trace"writeTo="allfile"/>
  19. <!--Skip Microsoft logs and so log only own logs-->
  20. <loggername="Microsoft.*"minlevel="Trace"writeTo="blackhole"final="true"/>
  21. <loggername="*"minlevel="Trace"writeTo="ownFile-web"/>
  22. </rules>
  23. </nlog>

3.建立日志公共类方法Logger.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4.  
  5. namespace System
  6. {
  7.     public class Logger
  8.     {
  9.  
  10.         //写入操作日志
  11.         const string mainLogger = "logger";
  12.         /// <summary>
  13.         /// 输出操作日志到NLog
  14.         /// </summary>
  15.         public static void Info(string msg)
  16.         {
  17.             var logger = NLog.LogManager.GetLogger(mainLogger);
  18.             logger.Info(msg);
  19.         }
  20.         public static void Error(string msg)
  21.         {
  22.             var logger = NLog.LogManager.GetLogger(mainLogger);
  23.             logger.Error(msg);
  24.         }
  25.         public static void Debug(string msg)
  26.         {
  27.             var logger = NLog.LogManager.GetLogger(mainLogger);
  28.             logger.Debug(msg);
  29.         }
  30.         public static void Exception(Exception ex)
  31.         {
  32.             var logger = NLog.LogManager.GetLogger(mainLogger);
  33.             logger.Error(ex);
  34.         }
  35.     }
  36. }

 

============ 欢迎各位老板打赏~ ===========

本文版权归Bruce's Blog所有,转载引用请完整注明以下信息:
本文作者:Bruce
本文地址:.NET Core使用Nlog记录日志 | Bruce's Blog

发表评论

留言无头像?