實(shí)在被log4net折磨的無語了,就自己寫了一個(gè)簡單的日志記錄操作類。
源碼如下(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>
- /// 這里需要手動(dòng)修改 ErrorLog 是我在本地的日志文件夾名稱
- /// </summary>
- private static readonly string StrPath = Path.Combine(Application.StartupPath,"ErrorLog");
- /// <summary>
- /// 創(chuàng)建路徑 按天保存
- /// </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($"***************記錄時(shí)間【");
- 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">錯(cuò)誤信息</param>
- /// <param name="isDirect">是否需要直接保存 默認(rèn)為否(后臺(tái)處理)</param>
- public static void WriteLog(string strInfo,bool isDirect=false)
- {
- SaveDataLog(isDirect ? $"詳細(xì)信息:{strInfo}" : strInfo);
- }
- /// <summary>
- /// 寫日志
- /// </summary>
- /// <param name="ex">Exception 實(shí)例</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("行號(hào) ", StringComparison.Ordinal);
- string strRowIndex = strStack.Substring(index3 + indexMove, strStack.Length - index3 - indexMove);
- StringBuilder sb = new StringBuilder();
- sb.AppendLine();
- sb.Append($"出錯(cuò)位置:{strMethod} ");
- sb.Append($"(第{strRowIndex}行)");
- sb.AppendLine();
- sb.AppendLine($"異常信息:{ex.Message}");
- sb.AppendLine($"詳細(xì)信息:{ex.StackTrace}");
- SaveDataLog(sb.ToString());
- }
- }
- }
調(diào)用示例:
- private void TestLog()
- {
- try
- {
- int a = 3;
- int b = 0;
- int c = a / b;
- }
- catch (Exception ex)
- {
- FuncMyLog.WriteLog(ex);
- }
- }
效果圖:聯(lián)系客服