Encapsulate a NLog + NLog. Mongo-based logging tool LogUtil and nloglogutil

Source: Internet
Author: User

Encapsulate a NLog + NLog. Mongo-based logging tool LogUtil and nloglogutil

Encapsulate an object based on NLog + NLog. the Mongo Logging Tool class is LogUtil. The code is relatively simple. It mainly integrates the logging target configuration and FileTarget configuration into the class, and uses the cache dependency to determine whether to re-create the Logger class, the complete code is as follows:

Using NLog; using NLog. config; using NLog. mongo; using NLog. targets; 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> // log tool class (based on NLog. mongo component) // Author: Zuo Wenjun // 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 mong ODbName = defaultMongoDbName; private string mongoDbCollectionName = ""; private bool asyncWriteLog = true; public static LogUtil GetInstance (string mongoDbCollName, string delimiter = null, bool needWriteLogToFile = true) {string key = string. format ("{0 }_{ 1}", defaultMongoDbName, mongoDbCollName); return cacheLogUitls. getOrAdd (key, new LogUtil () {LoggerCacheDependencyFilePat H = string. IsNullOrEmpty (loggerCacheDependencyFilePath )? HttpContext. Current. Server. MapPath ("~ /Web. config "): Response, NeedWriteLogToFile = needWriteLogToFile, MongoDbName = defaultmongomongodbname, MongoDbCollectionName = mongoDbCollName});} public string response {get {return response;} set {if (! File. exists (value) {throw new FileNotFoundException ("log configuration cache dependent file does not exist:" + value);} string oldValue = loggerCacheDependencyFilePath; loggerCacheDependencyFilePath = value; PropertyChanged, response) ;}} public bool NeedWriteLogToFile {get {return needWriteLogToFile;} set {bool oldValue = needWriteLogToFile; needWriteLogToFile = value; PropertyChanged (oldValue, need WriteLogToFile) ;}} public string MongoDbCollectionName {get {return mongoDbCollectionName;} set {string oldValue = mongoDbCollectionName; mongoDbCollectionName = value; PropertyChanged (oldValue, mongoDbCollectionName );}} /// <summary> /// only one DB is used for the same project, so it is not publicly available, take the default DB /// </summary> private string MongoDbName {get {return mongoDbName;} set {string oldValue = mongoDbName; mongoDbName = valu E; PropertyChanged (oldValue, mongoDbName) ;}} public bool AsyncWriteLog {get {return unknown ;}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. getdeleettingvalue ("MongoDbConnectionSet"); if (! String. isNullOrEmpty (mongoDbConnectionSet) {mongoDbConnectionSet = AESDecrypt (mongoDbConnectionSet); // decrypt the string. If the string is not encrypted, decryption is not required.} LoggingConfiguration config = new LoggingConfiguration (); # region configure the MONGODB log output object try {login target = new Login target (); login target. connectionString = mongoDbConnectionSet; mongoTarget. databaseName = mongoDbName; Specify target. collectionName = mongoDbCollectionName; Specified target. includeDefaults = false; appendlog=fields (Specify target. fields); Target Export targetnew = export Target; if (AsyncWriteLog) {export targetnew = WrapWithAsyncTargetWrapper (export Target); // wrap it as an asynchronous output object, for Asynchronous log WRITING} LoggingRule rule1 = new LoggingRule ("*", LogLevel. debug, export targetnew); config. loggingRules. add (rule1);} catch {}# endregion # region configure the log output object of 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 :1 {event-context: item = Other1}; Other2 :$ {event-context: item = Other2}; Other3 :$ {event-context: item = Other3} "; string procName = System. diagnostics. process. getCurrentProcess (). processName; fileTarget. F IleName = "$ {basedir}/Logs/" + procName + ". log "; fileTarget. archiveFileName = "$ {basedir}/archives/" + procName + ". {#}. log "; fileTarget. archiveNumbering = ArchiveNumberingMode. dateAndSequence; fileTarget. archiveAboveSize = 1024*1024*10; fileTarget. archiveDateFormat = "yyyyMMdd"; fileTarget. archiveEvery = FileArchivePeriod. day; fileTarget. maxArchiveFiles = 30; fileTarget. concurrentWrites = tr Ue; fileTarget. keepFileOpen = false; fileTarget. encoding = System. text. encoding. UTF8; Target fileTargetNew = fileTarget; if (AsyncWriteLog) {fileTargetNew = WrapWithAsyncTargetWrapper (fileTarget); // wrap it as an asynchronous output object, for Asynchronous log WRITING} LoggingRule rule2 = new LoggingRule ("*", LogLevel. debug, fileTargetNew); config. loggingRules. add (rule2);} catch {}# endregion LogManager. configuration = config; _ Logger = LogM Anager. getCurrentClassLogger (); HttpRuntime. cache. insert (cacheKey_NLogConfigFlag, "Nlog", new System. web. caching. cacheDependency (loggerCacheDependencyFilePath) ;}}return _ Logger;} private void appendlog=fields (IList <shortfield> shortfields) {shortfields. clear (); Type logPropertiesType = typeof (SysLogInfo. logProperties); foreach (var pro in typeof (SysLogInfo ). getProperties (BindingFlags. P Ublic | 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) {fields. add (new Parameter Field (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 ;}}}}

The purpose of encapsulating this log tool class is to ensure that the log format is uniform and can be quickly copied to various projects for use, this eliminates the need for configuration files or the inconsistency of log records due to configuration file modifications.

As can be seen from the Code, if the attribute changes, the cache ID will be invalid, meaning that the Logger object will be generated again, which ensures that the Logger is consistent with the configured rules at all times.

AsyncWriteLog is the asynchronous logging function. If it is based on the configuration file, you only need to change the async = "true" configuration in the configuration file targets to asynchronous. By default, both false and false are synchronous, but the Code does not introduce how to Implement Asynchronous online. I find the key point by analyzing the NLOG source code, that is, package it once through AsyncTargetWrapper asynchronous target package.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.