标签:
public static class SqlLog { /// <summary> /// 日志文件夹路径 /// </summary> private static string LogDic = HttpContext.Current.Server.MapPath("~/log/"); /// <summary> /// 锁标识 /// </summary> private static object obj = new object(); /// <summary> /// 同步插入系统日志 /// </summary> public static void WriteSQLLog(IDbCommand cmd) { try { string filePath = GetLogPath(); string logText = GetLogText(cmd); lock (obj) { using (StreamWriter streamWriter = File.Exists(filePath) ? File.AppendText(filePath) : File.CreateText(filePath)) { streamWriter.WriteLine(logText); streamWriter.Flush(); } } } catch { } } /// <summary> /// 异步插入日志 /// </summary> public static void WriteSQLLogAsync(IDbCommand cmd) { Task.Factory.StartNew(obj => WriteSQLLog((IDbCommand)obj), cmd); } /// <summary> /// 取得日志路径文件 /// </summary> public static string GetLogPath() { if (Directory.Exists(LogDic) == false) { Directory.CreateDirectory(LogDic); } return LogDic + string.Format(@"\{0}.log", DateTime.Now.ToString("yyyy-MM-dd")); } /// <summary> /// 获得日志内容 /// </summary> private static string GetLogText(IDbCommand cmd) { StringBuilder sb = new StringBuilder(); int index = 1; sb.AppendLine("******************************" + DateTime.Now + "*****************************************"); sb.AppendLine("sql:" + cmd.CommandText); foreach (dynamic item in cmd.Parameters) { sb.AppendLine(string.Format("parm{0}:" + item.Value, index++)); } return sb.ToString(); } }
标签:
原文地址:http://www.cnblogs.com/5tomorrow/p/5770111.html