码迷,mamicode.com
首页 > 数据库 > 详细

数据库操作日志

时间:2016-08-14 14:20:37      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

  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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!