using DBUtility; using System; using System.Data; using System.IO; using System.Text; /// /// LogHelper 的摘要说明 /// public class LogHelper { private static string CodeVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString().Trim(); // //保存日志的文件夹 // private static string logPath = AppDomain.CurrentDomain.BaseDirectory + @"log\"; /// /// 写日志 /// /// /// public static void WriteLog(string msg, string errorFile = "") { try { if (string.IsNullOrEmpty(msg)) { return; } else { msg = string.Format("程序版本号:{0},Time:{1},Message:{2}", CodeVersion, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), msg); } //如果不存在log文件夹 则创建 if (!Directory.Exists(logPath)) { Directory.CreateDirectory(logPath); } StreamWriter sw = File.AppendText(logPath + errorFile + DateTime.Now.ToString("yyyyMMdd") + ".Log"); sw.WriteLine(msg); sw.Close(); } catch (Exception ex) { } } /// /// 拼接错误日志 /// /// 异常类 /// 异常类文件夹名,可为空 public static void WriteLogManager(Exception ex, string errorFile = "") { StringBuilder str = new StringBuilder();//保存到文件中的日志信息 str.AppendLine("****************************异常文本****************************"); str.AppendLine("【程序版本号】:" + CodeVersion + " 【出现时间】:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); if (ex != null) { str.AppendLine(string.Format("【异常类型】:{0}\r\n【异常信息】:{1}\r\n【异常方法】:{2}\r\n【堆栈调用】:{3}", ex.GetType().Name, ex.Message, ex.TargetSite, ex.StackTrace)); } else { str.AppendLine(string.Format("【未处理应用程序线程错误】:{0}", ex)); } str.AppendLine("****************************************************************"); //保存日志 WriteLog(str.ToString(), "Error" + errorFile); } /// /// 系统日志(写数据库) /// /// /// public static void WriteSysLogBase(string msg, string method) { try { if (msg.Contains("'")) { msg = msg.Replace("'", "''"); } string sql = @" INSERT INTO [dbo].[LogSys] ([ID] ,[SysContent] ,[SysSource] ,[CreateTime]) VALUES ((SELECT NEWID()) ,'" + msg + @"' ,'" + method + @"' ,(SELECT GETDATE())) "; SqlHelper.ExecuteNonQuery(SqlHelper.SqlConnString, CommandType.Text, sql, null); } catch (Exception ex) { //throw ex; } } /// /// 错误日志(写数据库) /// /// /// public static void WriteErrLogBase(string msg, string method) { try { string sql = @" INSERT INTO [dbo].[LogErr] ([ID] ,[ErrContent] ,[ErrSource] ,[ErrTime]) VALUES ((SELECT NEWID()) ,'" + msg + @"' ,'" + method + @"' ,(SELECT GETDATE())) "; SqlHelper.ExecuteNonQuery(SqlHelper.SqlConnString, CommandType.Text, sql, null); } catch (Exception ex) { //throw ex; } } }