/****************************** * 说明:本地日志帮助类 * 创建人:龚宇超 * 创建日期:2017-08-10 * 修改人: * 修改日期: * 修改备注: * 版本:1.0.0.0 ******************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.IO; namespace Lskj.Util { /// /// 日志类型 /// public enum LogType { Error, Warning, Notice } /// /// 日志帮助类 /// public class LogHelper { /// /// 日志文件存放文件夹 /// private string _dicPath { get { return AppDomain.CurrentDomain.BaseDirectory + "Log"; } } private string _pattern = ".txt"; /// /// 单个日志文件大小 /// private int _fileSize = 1024*2048; /// /// 日志队列 /// private Queue _logQueue = new Queue(); /// /// 日志队列锁 /// private object _queueLock = new object(); private object _objLock = new object(); /// /// 日志文件名列表 /// private List _fileList = new List(); private static LogHelper instance = null; public static LogHelper Instance { get { if (instance == null) { instance = new LogHelper(); instance.Start(); } return instance; } } public LogHelper() { if(Directory.Exists(_dicPath)) { _fileList.Clear(); foreach (string fileName in Directory.GetFiles(_dicPath,"*"+_pattern)) { string name = fileName.Substring(fileName.LastIndexOf("\\")+1); _fileList.Add(name); } } } public void Start() { Task.Factory.StartNew(()=> { WriteLogFunc(); }); } /// /// 说明:写入文件 /// 创建人:龚宇超 /// 创建日期:2017-08-10 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// private void WriteLogFunc() { while(true) { if (CurrentLogCount() > 0) { string strWriteLog = GetLog(); WriteLogToFile(strWriteLog); } else Thread.Sleep(1000); } } #region 日志队列使用方式 /// /// 说明:加入日志 /// 创建人:龚宇超 /// 创建日期:2017-08-10 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The string log. private void AddLog(string strLog) { lock (_queueLock) { _logQueue.Enqueue(strLog); } } /// /// 说明:获取日志 /// 创建人:龚宇超 /// 创建日期:2017-08-10 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// System.String. private string GetLog() { string strLog = ""; lock (_queueLock) { if (_logQueue.Count > 0) strLog = _logQueue.Dequeue(); } return strLog; } /// /// 说明:当前队列条数 /// 创建人:龚宇超 /// 创建日期:2017-08-10 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// System.Int32. private int CurrentLogCount() { int count = 0; lock (_queueLock) { count = _logQueue.Count; } return count; } #endregion #region Method /// /// 说明:检查日志存放目录是否存在,如果不存在就创建 /// 创建人:龚宇超 /// 创建日期:2017-08-10 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// true if [is directory exist]; otherwise, false. private bool IsDirectoryExist() { if(!Directory.Exists(_dicPath)) { try { Directory.CreateDirectory(_dicPath); } catch(Exception e) { return false; } } return true; } /// /// 说明:创建日志文件,如果已存在文件名就改变 /// 创建人:龚宇超 /// 创建日期:2017-08-10 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The file path. /// true if [is create log file] [the specified file path]; otherwise, false. private bool IsCreateLogFile(ref string filePath) { if(File.Exists(filePath)) { string fileName = Path.GetFileNameWithoutExtension(filePath); int number = 1; string dateFileName = DateTime.Now.ToShortDateString().Replace('/', '_'); while(true) { string tempName = string.Format("{0}.{1}{2}", dateFileName, number, _pattern); if (_fileList.Where(p => p == tempName).Count() == 0) break; number++; } filePath = _dicPath+"\\"+ string.Format("{0}.{1}{2}", dateFileName, number, _pattern); } try { FileStream fs = File.Create(filePath, _fileSize); fs.Close(); _fileList.Add(Path.GetFileName(filePath)); } catch(Exception e) { return false; } return true; } /// /// 说明:检查写入的内容是否超过文件的大小限制 /// 创建人:龚宇超 /// 创建日期:2017-08-10 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The file path. /// The write log. /// true if [is log content out of size] [the specified file path]; otherwise, false. private bool IsLogContentOutOfSize(string filePath,string writeLog) { FileInfo fInfo = new FileInfo(filePath); if(fInfo.Length + writeLog.Length < _fileSize) { return false; } return true; } /// /// 说明:检查日志目录下有没有最新的日志文件,没有就创建新的日文件 /// 创建人:龚宇超 /// 创建日期:2017-08-10 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// true if [is last file exist]; otherwise, false. private bool IsLastFileExist() { if(_fileList.Count == 0) { string filePath = _dicPath + "\\" + DateTime.Now.ToShortDateString().Replace('/','_')+_pattern; try { FileStream fs = File.Create(filePath,_fileSize); fs.Close(); _fileList.Add(Path.GetFileName(filePath)); } catch(Exception e) { return false; } } return true; } /// /// 说明:日志写入文件 /// 创建人:龚宇超 /// 创建日期:2017-08-10 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The write log. private void WriteLogToFile(string writeLog) { if (!IsDirectoryExist()) return; if (!IsLastFileExist()) return; string writeFilePath = _dicPath + "\\" + _fileList.Last(); if (!File.Exists(_dicPath + "\\" + DateTime.Now.ToShortDateString().Replace('/', '_') + _pattern)) { writeFilePath = _dicPath + "\\" + DateTime.Now.ToShortDateString().Replace('/', '_') + _pattern; if (!IsCreateLogFile(ref writeFilePath)) { return; } } if(IsLogContentOutOfSize(writeFilePath,writeLog)) { if(!IsCreateLogFile(ref writeFilePath)) { return; } } FileStream fstream = null; StreamWriter streamWriter = null; try { fstream = new FileStream(writeFilePath,FileMode.Append,FileAccess.Write,FileShare.ReadWrite); streamWriter = new StreamWriter(fstream,Encoding.UTF8); streamWriter.WriteLine(writeLog); streamWriter.Flush(); } catch(Exception e) { } finally { streamWriter.Close(); fstream.Close(); } } /// /// 说明:写入日志 /// 创建人:龚宇超 /// 创建日期:2017-08-10 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The object. /// Type of the log. public void WriteLog(object obj,LogType logType= LogType.Notice) { string strLog = ""; lock(_objLock) { strLog = obj.ToString(); } if (string.IsNullOrEmpty(strLog)) return; string strWriteLog = string.Format("{0:yyyy-MM-dd HH:mm:ss:fff}", DateTime.Now) + " " +string.Format("[{0}]",logType)+ strLog + Environment.NewLine; AddLog(strWriteLog); } /// /// 说明:写入日志 /// 创建人:龚宇超 /// 创建日期:2017-08-12 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The object. /// The title. /// Type of the log. public void WriteLog(object obj, string title, LogType logType = LogType.Notice) { string strLog = ""; lock (_objLock) { strLog = obj.ToString(); } if (string.IsNullOrEmpty(strLog)) return; string strWriteLog = string.Format("{0:yyyy-MM-dd HH:mm:ss:fff}", DateTime.Now) + " " + string.Format("[{0}]", logType) + " " + string.Format("[{0}]", title) + strLog + Environment.NewLine; AddLog(strWriteLog); } /// /// 说明:写入异常 /// 创建人:龚宇超 /// 创建日期:2017-08-12 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The object. /// Type of the log. public void WriteError(Exception exception, LogType logType = LogType.Error) { string strLog = ""; lock (_objLock) { strLog = exception.Message + "\r\n" + exception.StackTrace; } if (string.IsNullOrEmpty(strLog)) return; string strWriteLog = string.Format("{0:yyyy-MM-dd HH:mm:ss:fff}", DateTime.Now) + " " + string.Format("[{0}]", logType) + strLog + Environment.NewLine; AddLog(strWriteLog); } /// /// 说明:写入异常 /// 创建人:龚宇超 /// 创建日期:2017-08-12 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The exception. /// The title. /// Type of the log. public void WriteError(Exception exception, string title, LogType logType = LogType.Error) { string strLog = ""; lock (_objLock) { strLog = exception.Message + "\r\n" + exception.StackTrace; } if (string.IsNullOrEmpty(strLog)) return; string strWriteLog = string.Format("{0:yyyy-MM-dd HH:mm:ss:fff}", DateTime.Now) + " " + string.Format("[{0}]", logType) + " " + string.Format("[{0}]", title) + strLog + Environment.NewLine; AddLog(strWriteLog); } #endregion } }