封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil,nloglogutil
封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil,代码比较简单,主要是把MongoTarget的配置、FileTarget的配置集成到类中,同时利用缓存依赖来判断是否需要重新创建Logger类,完整代码如下:
- using NLog;
- using NLog.Config;
- using NLog.Mongo;
- using NLog.Targets;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Web;
- using System.Collections.Concurrent;
- using NLog.Targets.Wrappers;
- /// <summary>
- /// 日志工具类(基于NLog.Mongo组件)
- /// Author:左文俊
- /// Date:2017/12/11
- /// </summary>
- public class LogUtil
- {
- private NLog.Logger _Logger = null;
- private const string cacheKey_NLogConfigFlag = "NLogConfigFlag";
- private const string defaultMongoDbName = "SysLog";
- private static readonly object syncLocker = new object();
- private static readonly ConcurrentDictionary<string, LogUtil> cacheLogUitls = new ConcurrentDictionary<string, LogUtil>();
- private string loggerCacheDependencyFilePath = "";
- private bool needWriteLogToFile = true;
- private string mongoDbName = defaultMongoDbName;
- private string mongoDbCollectionName = "";
- private bool asyncWriteLog = true;
- public static LogUtil GetInstance(string mongoDbCollName, string loggerCacheDependencyFilePath = null, bool needWriteLogToFile = true)
- {
- string key = string.Format("{0}_{1}", defaultMongoDbName, mongoDbCollName);
- return cacheLogUitls.GetOrAdd(key, new LogUtil()
- {
- LoggerCacheDependencyFilePath = string.IsNullOrEmpty(loggerCacheDependencyFilePath) ? HttpContext.Current.Server.MapPath("~/Web.config") : loggerCacheDependencyFilePath,
- NeedWriteLogToFile = needWriteLogToFile,
- MongoDbName = defaultMongoDbName,
- MongoDbCollectionName = mongoDbCollName
- });
- }
- public string LoggerCacheDependencyFilePath
- {
- get
- {
- return loggerCacheDependencyFilePath;
- }
- set
- {
- if (!File.Exists(value))
- {
- throw new FileNotFoundException("日志配置缓存依赖文件不存在:" + value);
- }
- string oldValue = loggerCacheDependencyFilePath;
- loggerCacheDependencyFilePath = value;
- PropertyChanged(oldValue, loggerCacheDependencyFilePath);
- }
- }
- public bool NeedWriteLogToFile
- {
- get
- {
- return needWriteLogToFile;
- }
- set
- {
- bool oldValue = needWriteLogToFile;
- needWriteLogToFile = value;
- PropertyChanged(oldValue, needWriteLogToFile);
- }
- }
- public string MongoDbCollectionName
- {
- get
- {
- return mongoDbCollectionName;
- }
- set
- {
- string oldValue = mongoDbCollectionName;
- mongoDbCollectionName = value;
- PropertyChanged(oldValue, mongoDbCollectionName);
- }
- }
- /// <summary>
- /// 同一个项目只会用一个DB,故不对外公开,取默认DB
- /// </summary>
- private string MongoDbName
- {
- get
- {
- return mongoDbName;
- }
- set
- {
- string oldValue = mongoDbName;
- mongoDbName = value;
- PropertyChanged(oldValue, mongoDbName);
- }
- }
- public bool AsyncWriteLog
- {
- get
- {
- return asyncWriteLog;
- }
- set
- {
- bool oldValue = asyncWriteLog;
- asyncWriteLog = value;
- PropertyChanged(oldValue, asyncWriteLog);
- }
- }
- private void PropertyChanged<T>(T oldValue, T newValue) where T : IEquatable<T>
- {
- if (!oldValue.Equals(newValue) && _Logger != null)
- {
- lock (syncLocker)
- {
- _Logger = null;
- }
- }
- }
- private Logger GetLogger()
- {
- if (_Logger == null || HttpRuntime.Cache[cacheKey_NLogConfigFlag] == null)
- {
- lock (syncLocker)
- {
- if (_Logger == null || HttpRuntime.Cache[cacheKey_NLogConfigFlag] == null)
- {
- string mongoDbConnectionSet = ConfigUtil.GetAppSettingValue("MongoDbConnectionSet");
- if (!string.IsNullOrEmpty(mongoDbConnectionSet))
- {
- mongoDbConnectionSet = AESDecrypt(mongoDbConnectionSet);//解密字符串,若未加密则无需解密
- }
- LoggingConfiguration config = new LoggingConfiguration();
- #region 配置MONGODB的日志输出对象
- try
- {
- MongoTarget mongoTarget = new MongoTarget();
- mongoTarget.ConnectionString = mongoDbConnectionSet;
- mongoTarget.DatabaseName = mongoDbName;
- mongoTarget.CollectionName = mongoDbCollectionName;
- mongoTarget.IncludeDefaults = false;
- AppendLogMongoFields(mongoTarget.Fields);
- Target mongoTargetNew = mongoTarget;
- if (AsyncWriteLog)
- {
- mongoTargetNew = WrapWithAsyncTargetWrapper(mongoTarget);//包装为异步输出对象,以便实现异步写日志
- }
- LoggingRule rule1 = new LoggingRule("*", LogLevel.Debug, mongoTargetNew);
- config.LoggingRules.Add(rule1);
- }
- catch
- { }
- #endregion
- #region 配置File的日志输出对象
- if (NeedWriteLogToFile)
- {
- try
- {
- FileTarget fileTarget = new FileTarget();
- fileTarget.Layout = @"[${date}] <${threadid}> - ${level} - ${event-context:item=Source} - ${event-context:item=UserID}: ${message};
- StackTrace:${stacktrace};Other1:${event-context:item=Other1};Other2:${event-context:item=Other2};Other3:${event-context:item=Other3}";
- string procName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
- fileTarget.FileName = "${basedir}/Logs/" + procName + ".log";
- fileTarget.ArchiveFileName = "${basedir}/archives/" + procName + ".{#}.log";
- fileTarget.ArchiveNumbering = ArchiveNumberingMode.DateAndSequence;
- fileTarget.ArchiveAboveSize = * * ;
- fileTarget.ArchiveDateFormat = "yyyyMMdd";
- fileTarget.ArchiveEvery = FileArchivePeriod.Day;
- fileTarget.MaxArchiveFiles = ;
- fileTarget.ConcurrentWrites = true;
- fileTarget.KeepFileOpen = false;
- fileTarget.Encoding = System.Text.Encoding.UTF8;
- Target fileTargetNew = fileTarget;
- if (AsyncWriteLog)
- {
- fileTargetNew = WrapWithAsyncTargetWrapper(fileTarget);//包装为异步输出对象,以便实现异步写日志
- }
- LoggingRule rule2 = new LoggingRule("*", LogLevel.Debug, fileTargetNew);
- config.LoggingRules.Add(rule2);
- }
- catch
- { }
- }
- #endregion
- LogManager.Configuration = config;
- _Logger = LogManager.GetCurrentClassLogger();
- HttpRuntime.Cache.Insert(cacheKey_NLogConfigFlag, "Nlog", new System.Web.Caching.CacheDependency(loggerCacheDependencyFilePath));
- }
- }
- }
- return _Logger;
- }
- private void AppendLogMongoFields(IList<MongoField> mongoFields)
- {
- mongoFields.Clear();
- Type logPropertiesType = typeof(SysLogInfo.LogProperties);
- foreach (var pro in typeof(SysLogInfo).GetProperties(BindingFlags.Public | BindingFlags.Instance))
- {
- if (pro.PropertyType == logPropertiesType) continue;
- string layoutStr = string.Empty; //"${event-context:item=" + pro.Name + "}";
- if (pro.Name.Equals("ThreadID") || pro.Name.Equals("Level") || pro.Name.Equals("MachineName"))
- {
- layoutStr = "${" + pro.Name.ToLower() + "}";
- }
- else if (pro.Name.Equals("LogDT"))
- {
- layoutStr = "${date:format=yyyy-MM-dd HH\\:mm\\:ss}";
- }
- else if (pro.Name.Equals("Msg"))
- {
- layoutStr = "${message}";
- }
- if (!string.IsNullOrEmpty(layoutStr))
- {
- mongoFields.Add(new MongoField(pro.Name, layoutStr, pro.PropertyType.Name));
- }
- }
- }
- private Target WrapWithAsyncTargetWrapper(Target target)
- {
- var asyncTargetWrapper = new AsyncTargetWrapper();
- asyncTargetWrapper.WrappedTarget = target;
- asyncTargetWrapper.Name = target.Name;
- target.Name = target.Name + "_wrapped";
- target = asyncTargetWrapper;
- return target;
- }
- private LogEventInfo BuildLogEventInfo(LogLevel level, string msg, string source, string uid, string detailTrace = null, string other1 = null, string other2 = null, string other3 = null)
- {
- var eventInfo = new LogEventInfo();
- eventInfo.Level = level;
- eventInfo.Message = msg;
- eventInfo.Properties["DetailTrace"] = detailTrace;
- eventInfo.Properties["Source"] = source;
- eventInfo.Properties["Other1"] = other1;
- eventInfo.Properties["Other2"] = other2;
- eventInfo.Properties["Other3"] = other3;
- eventInfo.Properties["UserID"] = uid;
- return eventInfo;
- }
- public void Info(string msg, string source, string uid, string detailTrace = null, string other1 = null, string other2 = null, string other3 = null)
- {
- try
- {
- var eventInfo = BuildLogEventInfo(LogLevel.Info, msg, source, uid, detailTrace, other1, other2, other3);
- var logger = GetLogger();
- logger.Log(eventInfo);
- }
- catch
- { }
- }
- public void Warn(string msg, string source, string uid, string detailTrace = null, string other1 = null, string other2 = null, string other3 = null)
- {
- try
- {
- var eventInfo = BuildLogEventInfo(LogLevel.Warn, msg, source, uid, detailTrace, other1, other2, other3);
- var logger = GetLogger();
- logger.Log(eventInfo);
- }
- catch
- { }
- }
- public void Error(string msg, string source, string uid, string detailTrace = null, string other1 = null, string other2 = null, string other3 = null)
- {
- try
- {
- var eventInfo = BuildLogEventInfo(LogLevel.Error, msg, source, uid, detailTrace, other1, other2, other3);
- var logger = GetLogger();
- logger.Log(eventInfo);
- }
- catch
- { }
- }
- public void Error(Exception ex, string source, string uid, string other1 = null, string other2 = null, string other3 = null)
- {
- try
- {
- var eventInfo = BuildLogEventInfo(LogLevel.Error, ex.Message, source, uid, ex.StackTrace, other1, other2, other3);
- var logger = GetLogger();
- logger.Log(eventInfo);
- }
- catch
- { }
- }
- public void Log(LogLevel level, string msg, string source, string uid, string detailTrace = null, string other1 = null, string other2 = null, string other3 = null)
- {
- try
- {
- var eventInfo = BuildLogEventInfo(level, msg, source, uid, detailTrace, other1, other2, other3);
- var logger = GetLogger();
- logger.Log(eventInfo);
- }
- catch
- { }
- }
- public class SysLogInfo
- {
- public DateTime LogDT { get; set; }
- public int ThreadID { get; set; }
- public string Level { get; set; }
- public string Msg { get; set; }
- public string MachineName { get; set; }
- public LogProperties Properties { get; set; }
- public class LogProperties
- {
- public string Source { get; set; }
- public string DetailTrace { get; set; }
- public string UserID { get; set; }
- public string Other1 { get; set; }
- public string Other2 { get; set; }
- public string Other3 { get; set; }
- }
- }
- }
封装这个日志工具类的目的就是为了保证日志格式的统一,同时可以快速的复制到各个项目中使用,而省去需要配置文件或因配置文件修改导致日志记录信息不一致的情况。
从代码中可以看出,若一旦属性发生改变,则缓存标识会失效,意味着会重新生成Logger对象,这样保证了Logger时刻与设置的规则相同。
另一点就是异步日志记录功能AsyncWriteLog,如果是基于配置文件,则只需要更改配置文件targets中配置async="true"即为异步。默认或写false都为同步,而代码上如何实现异步网上并没有介绍,我通过分析NLOG源代码找到关键点,即通过AsyncTargetWrapper异步目标包裹器来包装一次即可。
封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil,nloglogutil的更多相关文章
- 封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil
封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil,代码比较简单,主要是把MongoTarget的配置.FileTarget的配置集成到类中,同时利用缓存依赖来判断是否需要重新创 ...
- Go/Python/Erlang编程语言对比分析及示例 基于RabbitMQ.Client组件实现RabbitMQ可复用的 ConnectionPool(连接池) 封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!
Go/Python/Erlang编程语言对比分析及示例 本文主要是介绍Go,从语言对比分析的角度切入.之所以选择与Python.Erlang对比,是因为做为高级语言,它们语言特性上有较大的相似性, ...
- C# 日志记录工具类--LogHelper.cs测试
C# 日志记录工具类:(适用于不想使用log4j等第三方的Log工具的时候,希望自己写个简单类实现)LogHelper.cs内容如下: using System; using System.Diagn ...
- 封装一个简单好用的打印Log的工具类And快速开发系列 10个常用工具类
快速开发系列 10个常用工具类 http://blog.csdn.net/lmj623565791/article/details/38965311 ------------------------- ...
- 一个基于POI的通用excel导入导出工具类的简单实现及使用方法
前言: 最近PM来了一个需求,简单来说就是在录入数据时一条一条插入到系统显得非常麻烦,让我实现一个直接通过excel导入的方法一次性录入所有数据.网上关于excel导入导出的例子很多,但大多相互借鉴. ...
- 代码片段:基于 JDK 8 time包的时间工具类 TimeUtil
摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “知识的工作者必须成为自己时间的首席执行官.” 前言 这次泥瓦匠带来的是一个好玩的基于 JDK ...
- LogHelper 日志记录帮助类
1.LogHelper 日志记录帮助类 using System; using System.Collections.Generic; using System.Linq; using System. ...
- 一个使用命令行编译Android项目的工具类
一个使用命令行编译Android项目的工具类 简单介绍 编译apk项目须要使用的几个工具,基本都在sdk中,它们各自是(Windows系统): 1.aapt.exe 资源打包工具 2.android. ...
- 基于AOP和ThreadLocal实现日志记录
基于AOP和ThreadLocal实现的一个日志记录的例子 主要功能实现 : 在API每次被请求时,可以在整个方法调用链路中记录一条唯一的API请求日志,可以记录请求中绝大部分关键内容.并且可以自定义 ...
随机推荐
- 校园电商项目3(基于SSM)——配置Maven
步骤一:添加必要文件夹 先在src/main/resources下添加两个文件夹 接着在webapp文件夹下添加一个resources文件夹存放我们的静态网页内容 WEB-INF里的文件是不会被客户端 ...
- nginx反向代理proxy_pass的问题
起因:今天企业部署一个项目,用的nginx做的反向代理,配置如下: 测试结果令人失望,IP:端口 能访问项目,域名:端口 也能访问 ,但是 域名/接口名 访问失败 ################## ...
- delphi中 dataset容易出错的地方
最近写delphi项目,用到的数据集中的dataset,一直修改exception啊,写下过程. 在对数据集进行任何操作之前,首先要打开数据集.要打开数据集,可以把Active属性设为True,例如: ...
- SECCON 2014 CTF:Shuffle
很简单的一道小题 dia看一下是ELF文件 运行之: St0CFC}4cNOeE1WOS !eoCE{ CC T2hNto 是一串乱七八糟的字符 ida看一下: 很简单的逻辑 v5和v6是随机生成的两 ...
- 使用layui 做后台管理界面,在Tab中的链接点击后添加一个新TAB的解决方法
给链接或按钮 添加 onclick="self.parent.addTab('百度','http://www.baidu.com','icon-add')" 如: <a h ...
- Spring4 MVC Hibernate4 maven集成
http://www.cnblogs.com/leiOOlei/p/3727859.html
- [代码]--给任意网站添加聊天功能,随时聊(fa)天(che)
感谢“topurl.cn”制作此功能并分享. 这是一段代码,在打开的网页中使用,可以加载一个外挂形式的聊天室功能, 就可以和同样访问此网站进行相同操作的网友进行聊(fa)天(che)了. 使用方法: ...
- fpm 打包教程
常用yum命令: Yum安装时需要安装到指定的文件夹,则需要 --installroot yum install --installroot=/usr/src/ vim 常用rpm命令: 常用yum仓 ...
- 洛谷P1916 小书童——蚂蚁大战
题目背景 小A在你的帮助下,开始“刷题”,他在小书童里发现了一款叫“蚂蚁大战”(又称蛋糕保卫战)的游戏.(你懂得) 题目描述 游戏中会出现n只蚂蚁,分别有a1,a2……an的血量,它们要吃你的蛋糕.当 ...
- 吉哥系列故事――恨7不成妻 HDU - 4507 数位dp
思路 和普通的DP不一样的是 这里求的是满足条件的数的平方的和 而数位DP只跟数每位是什么密切相关 所以要开一个结构 (多加一个 数的和sum 和平方和qsum)存一下各个状态的和的情况 dp[p ...