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);
}
}

.NETCORE 下使用 NLog的更多相关文章

  1. .Net Core Web/Console 下使用Nlog

    .Net Core Console 下使用Nlog 官方介绍: https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-C ...

  2. .NetCore 下开发独立的(RPL)含有界面的组件包 (六)实现业务功能

    .NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作 .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服 务 .NetCore 下开发独立的(RPL)含 ...

  3. .NetCore 下开发独立的(RPL)含有界面的组件包 (五)授权过滤参数处理

    .NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作 .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服 务 .NetCore 下开发独立的(RPL)含 ...

  4. .NetCore 下开发独立的(RPL)含有界面的组件包 (四)授权过滤

    .NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作 .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服 务 .NetCore 下开发独立的(RPL)含 ...

  5. .NetCore 下开发独立的(RPL)含有界面的组件包 (三)构建界面

    .NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作 .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服 务 .NetCore 下开发独立的(RPL)含 ...

  6. .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服务

    .NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作 .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服 务 .NetCore 下开发独立的(RPL)含 ...

  7. .NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作

    .NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作 .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服 务 .NetCore 下开发独立的(RPL)含 ...

  8. NetCore下模拟和使用Modbus工业通信协议

    Tips: 1.目前NetCore下与Modbus通信的框架主要选择了 Modbus.Net  https://github.com/parallelbgls/Modbus.Net 2.modbus是 ...

  9. .netcore下的微服务、容器、运维、自动化发布

    原文:.netcore下的微服务.容器.运维.自动化发布 微服务 1.1     基本概念 1.1.1       什么是微服务? 微服务架构是SOA思想某一种具体实现.是一种将单应用程序作为一套小型 ...

  10. QQ浏览器、搜狗浏览器等兼容模式下,Asp.NetCore下,Cookie、Session失效问题

    原文:QQ浏览器.搜狗浏览器等兼容模式下,Asp.NetCore下,Cookie.Session失效问题 这些狗日的浏览器在兼容模式下,保存Cookie会失败,是因为SameSiteMode默认为La ...

随机推荐

  1. 2019 香港区域赛 BDEG 题解

    B.Binary Tree 题意:给你一棵二叉树.有两个游戏者,回合制,他们每次可以删去这棵二叉树中的一棵满二叉树.求最后谁赢. 解法:每一棵满二叉树有奇数个节点,那么每次游戏者只能删去奇数个节点,所 ...

  2. 在Linux驱动中使用input子系统

    在Linux驱动中使用输入子系统 参考: https://www.cnblogs.com/lifexy/p/7553861.html https://www.cnblogs.com/linux-37g ...

  3. 在WPF中使用着色器

    概念类比 范畴 CPU GPU 二进制文件 .exe .cso / .ps 二进制指令 机器码 CSO(shader指令) 助记符 汇编 SL 高级语言 C# HLSL 高级语言文件 .cs .hls ...

  4. Python——比 Seaborn 更好的相关性热力图:Biokit Corrplot

    目录 前言:我们需要更好的相关性热力图 对比 Python Seaborn 与 R corrplot 传统的 Seaborn 相关性热力图 R 语言中的相关性热力图 关于 Biokit 简介 库的安装 ...

  5. java 编程思想--个人总结

    从应用开始思考----思考解题思路--将思路分解成一步一步的步骤-----根据每一步的步骤思考如何用代码实现-- -- 不要心急,可以一块一块来完成-- 最后再思考如何用代码实现每两块之间的连接--- ...

  6. Mybatis 中 foreach 的四种用法

    foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合. foreach元素的属性主要有 item,index,collection,open,separator,close. ...

  7. SpringBoot集成Knife4j

    Knife4j简介 Knife4j 官网地址:https://doc.xiaominfo.com/ knife4j 是为Java MVC框架集成Swagger生成Api文档的增强解决方案. Knife ...

  8. C# 获取指定年月的第一天和最后一天、获取本月的第一天和最后一天、获取当前日期的星期几等

    •获取指定年月的第一天 public static DateTime GetCurMonthFirstDay(string year,string mon) { DateTime AssemblDat ...

  9. Mac 每次都要执行source ~/.bash_profile 配置的环境变量才生效

    自己在 ~/.bash_profile 中配置环境变量, 可是每次重启终端后配置的不生效.需要重新执行 : $source ~/.bash_profile 发现zsh加载的是 ~/.zshrc文件,而 ...

  10. C#——接口

    先来看看微软官方对接口的定义与说明. 接口定义协定. 实现接口的类或结构必须遵循它的协定. 接口可以从多个基接口继承,类或结构可以实现多个接口. 接口可以包含方法.属性.事件和索引器. 接口本身不提供 ...