.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 ...
随机推荐
- Kubernetes(七)数据存储
数据存储 容器的生命周期可能很短,会被频繁地创建和销毁.容器在销毁时,保存在容器中的数据也会被清除.这种结果对用户来说,在某些情况下是不乐意看到的.为了持久化保存容器的数据,kubernetes引入了 ...
- docker-compose的使用和常用命令
Docker简介 Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的镜像中,然后发布到任何流行的 Linux或Windows操作系统的机器上,也可以实现虚拟化. ...
- 开发一个微信小程序流程及需要多少费用?
流程如下: 小程序是一种新的开放能力,开发者可以快速地开发一个小程序.小程序可以在微信内被便捷地获取和传播,同时具有出色的使用体验. 开放注册范围:个人 企业 政府 媒体 其他组织 1.注册 在微信公 ...
- null 和 undefined 的区别?
null 表示一个对象被定义了,值为"空值":undefined 表示不存在这个值.(1)变量被声明了,但没有赋值时,就等于undefined. (2) 调用函数时,应该提供的参数 ...
- SeaweedFS + TiKV 部署保姆级教程
在使用 JuiceFS 时,我们选择了 SeaweedFS 作为对象存储,以及 TiKV 作为元数据存储,目前在 SeaweedFS 上已经存储了近1.5PB 的数据.关于 SeaweedFS 和 T ...
- 那些血淋淋的教训——math
1. 方程的解要写 x= 2023.12.10 晚上周测填空题第 \(2\) 题,方程的解写成了 \(7\) 而不是 \(x=7\). 2. 分类讨论 选填的最后一题. 3. 去绝对值看清楚符号(某个 ...
- Fiddler+proxifier解决抓取不到客户端接口的问题
工作中偶尔会遇到Fiddler抓不到客户端接口问题,那么就要借助第三方工具proxifier来实现了: 下载地址: 原地址:链接: https://pan.baidu.com/s/1JPJ4cILEs ...
- 微服务集成springsecurity实现认证
module:auth 1.添加依赖:spring-cloud-starter-security与spring-cloud-starter-oauth2 2.配置WebSecurityConfig:注 ...
- postfix&dovecot搭建邮件服务器
本篇参考 https://blog.51cto.com/5001660/2377785和小翔博客https://www.liuyixiang.com/post/113927.html. 邮件发送和接受 ...
- HIC simple process
1,什么是Hic数据? Hi-C是研究染色质三维结构的一种方法.Hi-C技术源于染色体构象捕获(Chromosome Conformation Capture, 3C)技术,利用高通量测序技术,结合生 ...