#region using System; using System.IO; using System.Text; using System.Windows.Forms; #endregion namespace CSFrameworkV5.Common { /// /// 系统异常日志,存放本地文件 /// public class LogLocalException : ILogUserOperate { private static LogLocalException _Instance; private string _LogFile; private int ITEM_COUNT = 3; //每行字符的项目数 private string SEPERATOR = " | "; //分隔符 private int TIME_INDEX = 0; //时间部分所在每行的序号 public LogLocalException(string file) { _LogFile = file; } public static LogLocalException Log { get { if (_Instance == null) { var logFile = Application.StartupPath + Globals.DEF_LOCAL_LOG; _Instance = new LogLocalException(logFile); } return _Instance; } } #region IOperateLog Members public void WriteLog(LogTypeSystem type, string content) { WriteLog(type.ToStringEx() + ":" + content); } public void WriteLog(LogTypeSystem type, string content, string formName, string formCaption, string menuName) { //打开窗体不写入本地日志 } public void ClearLog(string user, DateTime beginDate, DateTime endDate) { ClearLog(beginDate, endDate); } public void WriteLog(string content) { try { if (string.IsNullOrEmpty(content)) return; content = content.Replace("\r", " "); //去掉回车符 content = content.Replace("\n", " "); //去掉新行 // //日志格式:时间 | 日志内容 | 当前用户 // 举例:2013-08-02 18:34:56 | 未将对象引用实例. | admin // var time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); var line = time + SEPERATOR + content + SEPERATOR + "\r\n"; //断行符 //写入文件 File.AppendAllText(_LogFile, line, Encoding.UTF8); } catch { //不处理异常 } } public void ClearLog(DateTime beginDate, DateTime endDate) { try { var lines = File.ReadAllLines(_LogFile, Encoding.UTF8); DateTime date; string[] items; var sb = new StringBuilder(); foreach (var line in lines) { items = line.Split(new[] { SEPERATOR }, StringSplitOptions.None); if (items.Length == ITEM_COUNT) { //匹配时间 if (DateTime.TryParse(items[TIME_INDEX], out date)) if (date < beginDate || date > endDate) sb.AppendLine(line); //不在范围内,保留日志 } else { sb.AppendLine(line); } } //写入文件 File.WriteAllText(_LogFile, sb.ToStringEx(), Encoding.UTF8); } catch { //不处理异常 } } public void ClearAll() { try { File.WriteAllText(_LogFile, "", Encoding.UTF8); } catch { //不处理异常 } } #endregion } }