快捷搜索:

您的位置:澳门新葡4473网站 > 项目 > 写日志类

写日志类

发布时间:2019-12-18 23:02编辑:项目浏览(144)

    自己写了一个日志类用是可以用就是不知道哪里有需要优化的还有,现有写法有内存泄露的可能吗?

    publicclassLogInfo{publicstringAddTime;publicobjectContent;publicstringType;publicLogInfo(stringaddTime,objectcontent,stringtype){AddTime=addTime;Content=content;Type=type;}}interfaceILogger{voidWarn(objectmsg);voidInfo(objectmsg);voidDebug(objectmsg);voidError(objectmsg);}publicclassSimpleLogger:ILogger{//貌似ConcurrentQueue在framework低版本有问题,使用StrongBox在出列后标记其值为NULLprivateConcurrentQueueStrongBoxLogInfo_queue=newConcurrentQueueStrongBoxLogInfo();privatereadonlystring_filePath=$@"{AppDomain.CurrentDomain.BaseDirectory}Logs";privatebool_bThreadState=true;//使用Lazy创建线程安全单例模式//如果不用Lazy,则需要lock来判断对象是否需要实例化privatestaticreadonlyLazySimpleLogger_instance=newLazySimpleLogger(()=newSimpleLogger());publicstaticSimpleLoggerInstance=_instance.Value;privateSimpleLogger(){Task.Factory.StartNew(HandleLogQueue);}///summary///关闭日志队列线程////summarypublicvoidCloseLogThread(){_bThreadState=false;}///summary///判断日志队列是否为空////summary///returns/returnspublicboolQueueIsEmpty(){return_queue.IsEmpty;}publicvoidDebug(objectmsg){_queue.Enqueue(newStrongBoxLogInfo(newLogInfo(DateTime.Now.ToString("yyyy-MM-ddHH:mm:ss.fff"),msg,"Debug")));}publicvoidWarn(objectmsg){_queue.Enqueue(newStrongBoxLogInfo(newLogInfo(DateTime.Now.ToString("yyyy-MM-ddHH:mm:ss.fff"),msg,"Warn")));}publicvoidInfo(objectmsg){_queue.Enqueue(newStrongBoxLogInfo(newLogInfo(DateTime.Now.ToString("yyyy-MM-ddHH:mm:ss.fff"),msg,"Info")));}publicvoidError(objectmsg){_queue.Enqueue(newStrongBoxLogInfo(newLogInfo(DateTime.Now.ToString("yyyy-MM-ddHH:mm:ss.fff"),msg,"Error")));}privatevoidHandleLogQueue(){try{while(true){if(_queue.IsEmpty){if(!_bThreadState){break;}Thread.Sleep(10);}elseif(_queue.TryDequeue(outStrongBoxLogInfologInfo)){WriteLine(logInfo.Value.Content,logInfo.Value.Type,logInfo.Value.AddTime);logInfo.Value=null;}}}catch{//ignored}}privatevoidWriteLine(objectobj,stringcategory,stringtime){stringpath=$@"{_filePath}{DateTime.Now.ToString("yyyyMMdd")}";if(!Directory.Exists(path)){Directory.CreateDirectory(path);}//File.AppendAllText(path+$"Log-{category}.txt",Format(obj,category,time));using(StreamWritersw=newStreamWriter(path+$"Log-{category}.txt",true,Encoding.UTF8)){sw.WriteLine(Format(obj,category,time));}}privatestringFormat(objectobj,stringcategory,stringtime){StringBuilderbuilder=newStringBuilder();builder.AppendFormat("{0}",time);if(!string.IsNullOrEmpty(category)){builder.AppendFormat("[{0}]",category);}if(objisException){varex=objasException;builder.Append(ex.Message+"rn");builder.Append(ex.StackTrace+"rn");}else{builder.Append(obj+"rn");}returnbuilder.ToString();}}
    

    本文由澳门新葡4473网站发布于项目,转载请注明出处:写日志类

    关键词: