实在被log4net折磨的无语了,就自己写了一个简单的日志记录操作类。
源码如下(VS2015):
/************************************************** * 作者: 贾胜杰(2017/11/24/周五 9:22:34 ) **************************************************/ using System.Windows.Forms; public static class FuncMyLog /// 这里需要手动修改 ErrorLog 是我在本地的日志文件夹名称 private static readonly string StrPath = Path.Combine(Application.StartupPath,"ErrorLog"); private static string CreatePath() if (!Directory.Exists(StrPath)) Directory.CreateDirectory(StrPath); return $"{StrPath}\\{DateTime.Now.ToString("yyyy-MM-dd")}.log"; /// <param name="strInfo">文本信息</param> private static void SaveDataLog(string strInfo) StringBuilder sb = new StringBuilder(); sb.Append($"***************记录时间【"); sb.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")); sb.Append("】***************"); StreamWriter sw = new StreamWriter(CreatePath(), true, Encoding.Default); /// <param name="strInfo">错误信息</param> /// <param name="isDirect">是否需要直接保存 默认为否(后台处理)</param> public static void WriteLog(string strInfo,bool isDirect=false) SaveDataLog(isDirect ? $"详细信息:{strInfo}" : strInfo); /// <param name="ex">Exception 实例</param> public static void WriteLog(Exception ex) if (string.IsNullOrWhiteSpace(ex?.StackTrace)) return; string strStack = ex.StackTrace; int index1 = strStack.LastIndexOf(" 在 ", StringComparison.Ordinal); int index2 = strStack.LastIndexOf(" 位置 ", StringComparison.Ordinal); string strMethod = strStack.Substring(index1 + indexMove, index2 - index1 - indexMove); int index3 = strStack.LastIndexOf("行号 ", StringComparison.Ordinal); string strRowIndex = strStack.Substring(index3 + indexMove, strStack.Length - index3 - indexMove); StringBuilder sb = new StringBuilder(); sb.Append($"出错位置:{strMethod} "); sb.Append($"(第{strRowIndex}行)"); sb.AppendLine($"异常信息:{ex.Message}"); sb.AppendLine($"详细信息:{ex.StackTrace}"); SaveDataLog(sb.ToString());
调用示例:
效果图:
|