.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);
}
}
.NETCORE 下使用 NLog的更多相关文章
- .Net Core Web/Console 下使用Nlog
.Net Core Console 下使用Nlog 官方介绍: https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-C ...
- .NetCore 下开发独立的(RPL)含有界面的组件包 (六)实现业务功能
.NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作 .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服 务 .NetCore 下开发独立的(RPL)含 ...
- .NetCore 下开发独立的(RPL)含有界面的组件包 (五)授权过滤参数处理
.NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作 .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服 务 .NetCore 下开发独立的(RPL)含 ...
- .NetCore 下开发独立的(RPL)含有界面的组件包 (四)授权过滤
.NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作 .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服 务 .NetCore 下开发独立的(RPL)含 ...
- .NetCore 下开发独立的(RPL)含有界面的组件包 (三)构建界面
.NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作 .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服 务 .NetCore 下开发独立的(RPL)含 ...
- .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服务
.NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作 .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服 务 .NetCore 下开发独立的(RPL)含 ...
- .NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作
.NetCore 下开发独立的(RPL)含有界面的组件包 (一)准备工作 .NetCore 下开发独立的(RPL)含有界面的组件包 (二)扩展中间件及服 务 .NetCore 下开发独立的(RPL)含 ...
- NetCore下模拟和使用Modbus工业通信协议
Tips: 1.目前NetCore下与Modbus通信的框架主要选择了 Modbus.Net https://github.com/parallelbgls/Modbus.Net 2.modbus是 ...
- .netcore下的微服务、容器、运维、自动化发布
原文:.netcore下的微服务.容器.运维.自动化发布 微服务 1.1 基本概念 1.1.1 什么是微服务? 微服务架构是SOA思想某一种具体实现.是一种将单应用程序作为一套小型 ...
- QQ浏览器、搜狗浏览器等兼容模式下,Asp.NetCore下,Cookie、Session失效问题
原文:QQ浏览器.搜狗浏览器等兼容模式下,Asp.NetCore下,Cookie.Session失效问题 这些狗日的浏览器在兼容模式下,保存Cookie会失败,是因为SameSiteMode默认为La ...
随机推荐
- 高通平台mm-camera上电时序
高通平台mm-camera上电时序 背景 作为高通平台Camera知识的一种补充. 参考文档:https://blog.csdn.net/m0_37166404/article/details/649 ...
- Linux上快速安装 RabbitMQ
1.默认安装最新版,安装erlang apt-get install erlang 2.安装最新版 rabbitmq sudo apt-get update sudo apt-get install ...
- mybatis log4j打印sql语句
依赖 <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</a ...
- 做独立开发者,能在 AppStore 赚到多少钱?
成为一名独立开发者,不用朝九晚五的上班,开发自己感兴趣的产品,在AppStore里赚美金,这可能是很多程序员的梦想,今天就来盘一盘,这个梦想实现的概率有多少. (Solo社区 投稿) 先来了解一些数据 ...
- [oeasy]python0027_整合程序_延迟输出时间_整合两个py程序
整合程序 回忆上次内容 通过搜索发现 time中有函数可以延迟 time.sleep(1) 还可以让程序无限循环 while True: 现在需要两个程序的整合 循环延迟输出 时间输出 编辑 ...
- 使用Cloudflare Worker加速docker镜像
前言 开发者越来越难了,现在国内的docker镜像也都️了,没有镜像要使用docker太难了,代理又很慢 现在就只剩下自建镜像的办法了 GitHub上有开源项目可以快速搭建自己的镜像库,不过还是有点麻 ...
- AT_abc215_d 题解
洛谷链接&Atcoder 链接 本篇题解为此题较简单做法及较少码量,并且码风优良,请放心阅读. 题目简述 给定 \(N\),\(M\) 及含有 \(N\) 个整数的序列 \(A\). 求 \( ...
- gist.github.com 无法访问解决办法,亲测永远有效!
1.打开https://www.ipaddress.com/,输入gist.github.com获取IP地址 2.ping 此ip地址,可以访问 3.将IP地址写入Hosts文件,140.82.113 ...
- SpringBoot 配置统一API对象返回
1.前言 在实际项目开发中,为了便于前端进行响应处理,需要统一返回类格式.特别是在有多个后端开发人员参与的情况下,如果不规范返回类,每个人按照个人习惯返回数据,前端将面临各式各样的返回数据,难以统一处 ...
- 8、IDEA集成Git
8.1.配置Git忽略文件 8.1.1.忽略文件的原因 在使用 IDE 工具时,会自动生成一些和项目源码无关的文件,所以可以让 Git 忽略这些文件. 此外,把这些无关文件忽略掉,还能够屏蔽不同 ID ...