实在被log4net折磨的无语了,就自己写了一个简单的日志记录操作类。
源码如下(VS2015):
- /**************************************************
- *
- *命名空间: Common
- * 类名: FuncMyLog
- * 作者: 贾胜杰(2017/11/24/周五 9:22:34 )
- *模块说明: 自定义日志类
- *修改日志:
- *
- **************************************************/
- using System;
- using System.IO;
- using System.Text;
- using System.Windows.Forms;
- namespace Common
- {
- public static class FuncMyLog
- {
- /// <summary>
- /// 这里需要手动修改 ErrorLog 是我在本地的日志文件夹名称
- /// </summary>
- private static readonly string StrPath = Path.Combine(Application.StartupPath,"ErrorLog");
- /// <summary>
- /// 创建路径 按天保存
- /// </summary>
- /// <returns></returns>
- private static string CreatePath()
- {
- if (!Directory.Exists(StrPath))
- Directory.CreateDirectory(StrPath);
- return $"{StrPath}\\{DateTime.Now.ToString("yyyy-MM-dd")}.log";
- }
- /// <summary>
- /// 以流的方式保存文件
- /// </summary>
- /// <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("】***************");
- sb.AppendLine(strInfo);
- StreamWriter sw = new StreamWriter(CreatePath(), true, Encoding.Default);
- sw.Write(sb);
- sw.Flush();
- sw.Close();
- }
- /// <summary>
- /// 写日志
- /// </summary>
- /// <param name="strInfo">错误信息</param>
- /// <param name="isDirect">是否需要直接保存 默认为否(后台处理)</param>
- public static void WriteLog(string strInfo,bool isDirect=false)
- {
- SaveDataLog(isDirect ? $"详细信息:{strInfo}" : strInfo);
- }
- /// <summary>
- /// 写日志
- /// </summary>
- /// <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);
- int indexMove = 3;
- 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.AppendLine();
- sb.Append($"出错位置:{strMethod} ");
- sb.Append($"(第{strRowIndex}行)");
- sb.AppendLine();
- sb.AppendLine($"异常信息:{ex.Message}");
- sb.AppendLine($"详细信息:{ex.StackTrace}");
- SaveDataLog(sb.ToString());
- }
- }
- }
调用示例:
- private void TestLog()
- {
- try
- {
- int a = 3;
- int b = 0;
- int c = a / b;
- }
- catch (Exception ex)
- {
- FuncMyLog.WriteLog(ex);
- }
- }
效果图:联系客服