.NETCORE 下使用 NLog

NLog幫助類

 1  public enum LogType
 2     {
 3         [Description("網站")]
 4         Web,
 5         [Description("數據庫")]
 6         DataBase,
 7         [Description("Api接口")]
 8         ApiRequest,
 9         [Description("中間件")]
10         Middleware
11     }
12     public static class NLogUtil
13     {
14         public static Logger dbLogger = LogManager.GetLogger("logdb");
15         public static Logger fileLogger = LogManager.GetLogger("logfile");
16 
17         /// <summary>
18         /// 寫日誌到數據庫
19         /// </summary>
20         /// <param name="logLevel">日誌等級</param>
21         /// <param name="logType">日誌類型</param>
22         /// <param name="message">信息</param>
23         /// <param name="exception">異常</param>
24         public static void WriteDBLog(LogLevel logLevel, LogType logType, string message, Exception exception = null, HttpContext httpcontext = null)
25         {
26             LogEventInfo theEvent = new LogEventInfo(logLevel, dbLogger.Name, message);
27             theEvent.Properties["LogType"] = logType.ToString();
28             if (httpcontext != null)
29             {
30                 theEvent.Properties["MachineIp"] = httpcontext.Request.UserHostAddress.ToString();
31                 theEvent.Properties["NetRequestMethod"] = httpcontext.Request.HttpMethod.ToString();
32                 theEvent.Properties["NetRequestUrl"] = httpcontext.Request.Url.ToString();
33             }
34             theEvent.Exception = exception;
35             dbLogger.Log(theEvent);
36         }
37 
38         /// <summary>
39         /// 寫日誌到文件
40         /// </summary>
41         /// <param name="logLevel">日誌等級</param>
42         /// <param name="logType">日誌類型</param>
43         /// <param name="message">信息</param>
44         /// <param name="exception">異常</param>
45         public static void WriteFileLog(LogLevel logLevel, LogType logType, string message, Exception exception = null, HttpContext httpcontext = null)
46         {
47             LogEventInfo theEvent = new LogEventInfo(logLevel, fileLogger.Name, message);
48             theEvent.Properties["LogType"] = logType.ToString();
49             if (httpcontext != null)
50             {
51                 theEvent.Properties["MachineIp"] = httpcontext.Request.UserHostAddress.ToString();
52                 theEvent.Properties["NetRequestMethod"] = httpcontext.Request.HttpMethod.ToString();
53                 theEvent.Properties["NetRequestUrl"] = httpcontext.Request.Url.ToString();
54             }
55             theEvent.Exception = exception;
56             fileLogger.Log(theEvent);
57         }
58         /// <summary>
59         /// 確保NLog配置文件sql連接字符串正確
60         /// </summary>
61         /// <param name="nlogPath"></param>
62         /// <param name="sqlConnectionStr"></param>
63         public static void EnsureNlogConfig(string nlogPath, string sqlConnectionStr)
64         {
65             XDocument xd = XDocument.Load(nlogPath);
66             if (xd.Root.Elements().FirstOrDefault(a => a.Name.LocalName == "targets")
67                 is XElement targetsNode && targetsNode != null &&
68                 targetsNode.Elements().FirstOrDefault(a => a.Name.LocalName == "target" && a.Attribute("name").Value == "log_database")
69                 is XElement targetNode && targetNode != null)
70             {
71                 if (!targetNode.Attribute("connectionString").Value.Equals(sqlConnectionStr))//不一致則修改
72                 {
73                     //這裏暫時沒有考慮dbProvider的變動
74                     targetNode.Attribute("connectionString").Value = sqlConnectionStr;
75                     xd.Save(nlogPath);
76                     //編輯後重新載入配置文件(不依靠NLog自己的autoReload,有延遲)
77                     LogManager.Configuration = new XmlLoggingConfiguration(nlogPath);
78                 }
79             }
80         }
81     }

nlog.config配置文件

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true">
 3   <targets>
 4     <target name="log_database" xsi:type="Database"  dbProvider="MySql.Data.MySqlClient.MySqlConnection,MySql.Data" connectionString="Server=192.168.3.209;Port=3306; Database=ismartecab_asrs; Connection Timeout=60; uid=ist;pwd=123456;">
 5       <commandText>
 6         INSERT INTO syslog_t
 7         (LogDate
 8         ,LogLevel
 9         ,LogType
10         ,Logger
11         ,Message
12         ,MachineName
13         ,MachineIp
14         ,NetRequestMethod
15         ,NetRequestUrl
16         ,NetUserIsauthenticated
17         ,NetUserAuthtype
18         ,NetUserIdentity
19         ,Exception)
20         VALUES
21         (@LogDate
22         ,@LogLevel
23         ,@LogType
24         ,@Logger
25         ,@Message
26         ,@MachineName
27         ,@MachineIp
28         ,@NetRequestMethod
29         ,@NetRequestUrl
30         ,@NetUserIsauthenticated
31         ,@NetUserAuthtype
32         ,@NetUserIdentity
33         ,@EXCEPTION);
34       </commandText>
35       <parameter name="@LogDate" layout="${date}" />
36       <parameter name="@LogLevel" layout="${level}" />
37       <parameter name="@LogType" layout="${event-properties:item=LogType}" />
38       <parameter name="@Logger" layout="${logger}" />
39       <parameter name="@Message" layout="${message}" />
40       <parameter name="@MachineName" layout="${machinename}" />
41       <parameter name="@MachineIp" layout="${event-properties:item=MachineIp}" />
42       <parameter name="@NetRequestMethod" layout="${event-properties:item=NetRequestMethod}" />
43       <parameter name="@NetRequestUrl" layout="${event-properties:item=NetRequestUrl}" />
44       <parameter name="@NetUserIsauthenticated" layout="${aspnet-user-isauthenticated}" />
45       <parameter name="@NetUserAuthtype" layout="${aspnet-user-authtype}" />
46       <parameter name="@NetUserIdentity" layout="${aspnet-user-identity}" />
47       <parameter name="@Exception" layout="${exception:tostring}" />
48     </target>
49     <target name="log_file" xsi:type="File" fileName="${basedir}/logs/${shortdate}.log" layout="======================================================================================================             ${newline}日期:${longdate}              ${newline}日誌類型: ${level:uppercase=false}             ${newline}客戶端IP: ${event-properties:item=MachineIp}             ${newline}請求方式: ${event-properties:item=NetRequestMethod}             ${newline}請求地址: ${event-properties:item=NetRequestUrl}             ${newline}錯誤消息: ${message} ${onexception:${exception:format=tostring}              ${newline}堆棧信息: ${stacktrace}" />
50   </targets>
51   <rules>
52     <!--跳過所有級別的Microsoft組件的日誌記錄-->
53     <logger name="Microsoft.*" final="true" />
54     <!-- BlackHole without writeTo -->
55     <!--只通過數據庫記錄日誌,如果給了name名字,cs裏用日誌記錄的時候,取logger需要把name當做參數-->
56     <logger name="logdb" writeTo="log_database" />
57     <logger name="logfile" writeTo="log_file" />
58   </rules>
59 </nlog>

使用示例

 NLogUtil.WriteDBLog(NLog.LogLevel.Info, LogType.ApiRequest, "API started successfully!", null, null);

全局異常

    public class ApiExceptionHandlingAttribute : ExceptionFilterAttribute
    {
        /// <summary>
        /// 統一對調用異常信息進行處理,返回自定義的異常信息
        /// </summary>
        /// <param name="context">HTTP上下文對象</param>
        public override void OnException(HttpActionExecutedContext context)
        {
            NLogUtil.WriteDBLog(NLog.LogLevel.Error, LogType.ApiRequest, context.Exception.Message, context.Exception, HttpContext.Current);
            base.OnException(context);
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章