using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Threading; namespace CommonTool { public class ThreadLog : IDisposable { //日志对象的缓存队列 private static Queue _msgs; //日志文件保存的路径 private static string _path; //日志写入线程的控制标记 private static bool _state; //日志记录的类型 private static LogType _type; //日志文件生命周期的时间标记 private static DateTime _timeSign; //日志文件写入流对象 private static StreamWriter _writer; Thread _thread; /// /// 创建日志对象的新实例,采用默认当前程序位置作为日志路径和默认的每日日志文件类型记录日志 /// public ThreadLog() : this(".\\", LogType.Daily) { } /// /// 创建日志对象的新实例,采用默认当前程序位置作为日志路径并指定日志类型 /// /// 日志文件创建方式的枚举 public ThreadLog(LogType t) : this(".\\", t) { } /// /// 创建日志对象的新实例,根据指定的日志文件路径和指定的日志文件创建类型 /// /// 日志文件保存路径 /// 日志文件创建方式的枚举 public ThreadLog(string p, LogType t) { if (_msgs == null) { _state = true; _path = p; _type = t; _msgs = new Queue(); _thread = new Thread(Work) {IsBackground = true}; //保证线程随主程序退出而退出 _thread.Start(); } } //日志文件写入线程执行的方法 private void Work() { while (true) { //判断队列中是否存在待写入的日志 if (_msgs.Count > 0) { Msg msg; lock (_msgs) { msg = _msgs.Dequeue(); } if (msg != null) { FileWrite(msg); } } else { //判断是否已经发出终止日志并关闭的消息 if (_state) { Thread.Sleep(1); } else { FileClose(); break; } } } if (_thread != null && _thread.IsAlive) { _thread.Abort(); _thread = null; } } //根据日志类型获取日志文件名,并同时创建文件到期的时间标记 //通过判断文件的到期时间标记将决定是否创建新文件。 private string GetFilename() { DateTime now = DateTime.Now; string format = ""; switch (_type) { case LogType.Daily: _timeSign = new DateTime(now.Year, now.Month, now.Day); _timeSign = _timeSign.AddDays(1); format = "yyyyMMdd'.log'"; break; case LogType.Weekly: _timeSign = new DateTime(now.Year, now.Month, now.Day); _timeSign = _timeSign.AddDays(7); format = "yyyyMMdd'.log'"; break; case LogType.Monthly: _timeSign = new DateTime(now.Year, now.Month, 1); _timeSign = _timeSign.AddMonths(1); format = "yyyyMM'.log'"; break; case LogType.Annually: _timeSign = new DateTime(now.Year, 1, 1); _timeSign = _timeSign.AddYears(1); format = "yyyy'.log'"; break; } return now.ToString(format); } //写入日志文本到文件的方法 private void FileWrite(Msg msg) { try { if (_writer == null) { FileOpen(); } //判断文件到期标志,如果当前文件到期则关闭当前文件创建新的日志文件 if (DateTime.Now >= _timeSign) { FileClose(); FileOpen(); } if (_writer != null) { Thread.Sleep(1); _writer.Write(msg.Datetime); _writer.Write('\t'); _writer.Write(msg.Type); _writer.Write('\t'); _writer.WriteLine(msg.Text); _writer.Flush(); } } catch (Exception e) { Console.Out.Write(e); } } //打开文件准备写入 private void FileOpen() { if (!Directory.Exists(_path)) Directory.CreateDirectory(_path); _writer = new StreamWriter(_path + GetFilename(), true, Encoding.UTF8); } //关闭打开的日志文件 private void FileClose() { if (_writer != null) { _writer.Flush(); _writer.Close(); _writer.Dispose(); _writer = null; } } public void WriteErr(string pcMsg) { Write(new Msg(pcMsg, LogMsgType.Error)); } public void WriteInfor(string pcMsg) { Write(new Msg(pcMsg, LogMsgType.Information)); } public void WriteSuccess(string pcMsg) { Write(new Msg(pcMsg, LogMsgType.Success)); } public void WriteUnknown(string pcMsg) { Write(new Msg(pcMsg, LogMsgType.Unknown)); } public void WriteWarning(string pcMsg) { Write(new Msg(pcMsg, LogMsgType.Warning)); } /// /// 写入新日志,根据指定的日志对象Msg /// /// 日志内容对象 public void Write(Msg msg) { if (msg != null) { lock (_msgs) { _msgs.Enqueue(msg); } } } /// /// 写入新日志,根据指定的日志内容和信息类型,采用当前时间为日志时间写入新日志 /// /// 日志内容 /// 信息类型 public void Write(string text, LogMsgType type) { Write(new Msg(text, type)); } /// /// 写入新日志,根据指定的日志时间、日志内容和信息类型写入新日志 /// /// 日志时间 /// 日志内容 /// 信息类型 public void Write(DateTime dt, string text, LogMsgType type) { Write(new Msg(dt, text, type)); } /// /// 写入新日志,根据指定的异常类和信息类型写入新日志 /// /// 异常对象 /// 信息类型 public void Write(Exception e, LogMsgType type) { Write(new Msg(e.Message, type)); } #region IDisposable 成员 /// /// 销毁日志对象 /// public void Dispose() { _state = false; } #endregion static ThreadLog _sysLog; public static ThreadLog SysLog { get { if (_sysLog == null) { string lcpath = AppConfig.DefConfig.ReadString("LOGPATH"); if (!string.IsNullOrEmpty(lcpath) && lcpath.Length > 0) { try { Directory.CreateDirectory(lcpath); } catch { // ignored } } _sysLog = Directory.Exists(lcpath) ? new ThreadLog(lcpath, LogType.Daily) : new ThreadLog(".\\Log\\", LogType.Daily); } return _sysLog; } } } public enum LogType { /// /// 此枚举指示每天创建一个新的日志文件 /// Daily, /// /// 此枚举指示每周创建一个新的日志文件 /// Weekly, /// /// 此枚举指示每月创建一个新的日志文件 /// Monthly, /// /// 此枚举指示每年创建一个新的日志文件 /// Annually } public class Msg { //日志记录的时间 private DateTime _datetime; //日志记录的内容 private string _text; //日志记录的类型 /// /// 创建新的日志记录实例;日志记录的内容为空,消息类型为MsgType.Unknown,日志时间为当前时间 /// public Msg() : this("", LogMsgType.Unknown) { } /// /// 创建新的日志记录实例;日志事件为当前时间 /// /// 日志记录的文本内容 /// 日志记录的消息类型 public Msg(string t, LogMsgType p) : this(DateTime.Now, t, p) { } /// /// 创建新的日志记录实例; /// /// 日志记录的时间 /// 日志记录的文本内容 /// 日志记录的消息类型 public Msg(DateTime dt, string t, LogMsgType p) { _datetime = dt; Type = p; _text = t; } /// /// 获取或设置日志记录的时间 /// public DateTime Datetime { get { return _datetime; } set { _datetime = value; } } /// /// 获取或设置日志记录的文本内容 /// public string Text { get { return _text; } set { _text = value; } } /// /// 获取或设置日志记录的消息类型 /// public LogMsgType Type { get; set; } public override string ToString() { return _datetime.ToString(CultureInfo.InvariantCulture) + "\t" + _text + "\n"; } } public enum LogMsgType { //[3:钥匙授权],[4:开锁记录],[5:资产登记],[6:资产编码],[7:人员],[8:参数设置],[9:系统日志],[0:异常日志],[] /// /// 钥匙授权 /// Authorize = 3, /// /// 开锁记录 /// OpenLogs = 4, /// /// 资产登记 /// Register = 5, /// /// 资产编码 /// Coding = 6, /// /// 人员分组 /// Persons = 7, /// /// 参数设置 /// SysParameter = 8, /// /// 指示普通信息类型的日志记录 /// Information = 9, /// /// 指示警告信息类型的日志记录 /// Warning = 10, /// /// 指示未知信息类型的日志记录 /// Unknown = 99, /// /// 指示错误信息类型的日志记录 /// Error = 0, /// /// 指示成功信息类型的日志记录 /// Success = 1 } }