using Newtonsoft.Json; using System; using System.IO; using System.Collections; using System.Collections.Generic; namespace iWare_SCADA_BusinessLogical.Utils { public class LogTextHelper { /// /// 批次删除日志文件 /// public static void BatchDeleteLog() { List deleteFolder = new System.Collections.Generic.List(); string folderPath = @"d:\\Log"; FolderHelper.ListDirectory(folderPath, 0, ref deleteFolder); foreach (var item in deleteFolder) { FileHelper.DeleteOldFiles(item, 30);//删除一个月的数据 } } /// /// 批次删除日志文件 /// public static void BatchDeleteLog(string folderPath, int days) { List deleteFolder = new System.Collections.Generic.List(); FolderHelper.ListDirectory(folderPath, 0, ref deleteFolder); foreach (var item in deleteFolder) { FileHelper.DeleteOldFiles(item, days);//删除一个月的数据 } } /// /// 往日志里追加内容 /// /// 日志目录 /// 内容 private static void DoWriteLogContent(string folder, string logContent, Exception ex) { try { if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } string message = string.Format("【{0}】{1}\r\n", DateTime.Now.ToString("HH:mm:ss"), logContent); if (ex != null) { message += ",异常堆栈:" + JsonConvert.SerializeObject(ex); } File.AppendAllText(Path.Combine(folder, DateTime.Now.ToString("yyyyMMdd") + ".txt"), message); } catch (Exception) { } } /// /// 往日志里追加内容 /// /// 日志目录 /// 内容格式 /// 内容参数 public static void WriteLine(string folder, string format, params object[] args) { try { if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } string message = string.Format("【{0}】{1}\r\n", DateTime.Now.ToString("HH:mm:ss"), string.Format(format, args)); File.AppendAllText(Path.Combine(folder, DateTime.Now.ToString("yyyyMMdd") + ".txt"), message); } catch (Exception) { } } /// /// 添加日志 /// /// 日志目录 /// 类名 /// 方法名 /// 内容格式 /// 内容参数 public static void WriteLog(string folder, string className, string methodName, string format, params object[] args) { WriteLine(folder, "在类{0}的{1}方法中:{2}", className, methodName, string.Format(format, args)); } /// /// 写入日志 /// /// 日志目录 /// 类名 /// 方法名 /// 内容格式 /// 内容参数 public static void WriteLogContent(string folder, string className, string methodName, string logContent, Exception ex) { DoWriteLogContent(folder, string.Format("在类{0}的{1}方法中:{2}", className, methodName, logContent), ex); } } }