.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); } }
喜欢 C#、SQL、Web