引言
这是一个简单的自定义的错误日志记录类,这里我主要用于API接口开发中,APP移动端的入参记录
日志参数
/// <summary> /// 日志参数 /// </summary> public static class LogReq { /// <summary> /// 入参 /// </summary> public static string LogReqStr = ""; /// <summary> /// 加密后入参 /// </summary> public static string DesCryptStr = ""; /// <summary> /// 联众请求 /// </summary> public static string LogMintInfoStr = ""; }
定义参数
错误日志定义类
public class LogClass { private string logFile; private StreamWriter writer; private FileStream fileStream = null; private string ReqStr = LogReq.LogReqStr;//APP请求入参 private string DesCryptStr = LogReq.DesCryptStr;//APP请求入参[加密后] private string MediInfoReq = LogReq.LogMintInfoStr;//联众请求入参 public LogClass(string fileName) { logFile = fileName; CreateDirectory(logFile); } /// <summary> /// 系统错误报告 /// </summary> /// <param name="ex"></param> public void ExcLog(Exception ex) { try { FileInfo fileInfo = new FileInfo(logFile); if (!fileInfo.Exists) { fileStream = fileInfo.Create(); writer = new StreamWriter(fileStream); } else { fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write); writer = new StreamWriter(fileStream); } writer.WriteLine("当前时间:" + DateTime.Now); writer.WriteLine("加密后入参:" + DesCryptStr); writer.WriteLine("入参信息:" + ReqStr); writer.WriteLine("联众请求入参:" + MediInfoReq); writer.WriteLine("异常信息:" + ex.Message); writer.WriteLine("异常对象:" + ex.Source); writer.WriteLine("调用堆栈:\n" + ex.StackTrace.Trim()); writer.WriteLine("触发方法:" + ex.TargetSite); writer.WriteLine(); writer.Close(); } finally { if (writer != null) { writer.Close(); writer.Dispose(); fileStream.Close(); fileStream.Dispose(); } } } /// <summary> /// 自定义错误报告 /// </summary> /// <param name="ex"></param> public void ExcLog(CustomerException ex) { try { FileInfo fileInfo = new FileInfo(logFile); if (!fileInfo.Exists) { fileStream = fileInfo.Create(); writer = new StreamWriter(fileStream); } else { fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write); writer = new StreamWriter(fileStream); } writer.WriteLine("当前时间:" + DateTime.Now); writer.WriteLine("入参信息:" + ReqStr); writer.WriteLine("加密后入参:" + DesCryptStr); writer.WriteLine("联众请求入参:" + MediInfoReq); writer.WriteLine("异常代码:" + (int)ex.Code); writer.WriteLine("异常信息:" + ex.Msg); writer.WriteLine(); writer.Close(); } finally { if (writer != null) { writer.Close(); writer.Dispose(); fileStream.Close(); fileStream.Dispose(); } } } public void CreateDirectory(string infoPath) { DirectoryInfo directoryInfo = Directory.GetParent(infoPath); if (!directoryInfo.Exists) { directoryInfo.Create(); } } }
错误日志类
使用例子(指定路径)
var log = new Log.LogClass("E:\\website\\NanChang\\ExcLog\\" + DateTime.Now.ToString("yyyyMMdd") + "_Log.txt"); log.ExcLog(ex);
PS:如果需要自定义路劲的话,请自行修改哈
时间: 2024-10-14 21:26:07