apsky

apsky

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
public class LogHelper
    {
        #region 构造函数、析构函数、单一实体

        private LogHelper() 
        {
            _threadWriteLog = new Thread(new ThreadStart(WriteLog));
            _threadWriteLog.Start();
        }

        ~LogHelper()
        {
            if (_threadWriteLog != null)
            {
                _threadWriteLog.Abort();
                _threadWriteLog = null;
            }
        }

        private static LogHelper logHelper;
        private static readonly object sysRoot = new object();
        /// <summary>
        /// 日志类的单一实体
        /// </summary>
        public static LogHelper LogHelperSingle
        {
            get
            {
                if (logHelper == null)
                {
                    lock (sysRoot)
                    {
                        if (logHelper == null)
                        {
                            logHelper = new LogHelper();
                        }
                    }
                }
                return logHelper;
            }
        }

        #endregion

        #region 属性

        private string _path = string.Empty;
        /// <summary>
        /// 日志路径
        /// </summary>
        public string LogPath
        {
            set { this._path = value; }
            get
            {
                if (string.IsNullOrEmpty(this._path))
                {
                    this._path = string.Format("{0}\\Log", Application.StartupPath);
                }
                return this._path;
            }
        }

        private string _logName;
        /// <summary>
        /// 日志名称
        /// </summary>
        public string LogName
        {
            set { this._logName = value; }
            get
            {
                if (string.IsNullOrEmpty(this._logName))
                {
                    DateTime t = DateTime.Now;
                    this._logName = string.Format("{0}{1}{2}.txt", t.Year, t.Month, t.Day);
                }
                return this._logName;
            }
        }
        /// <summary>
        /// 日志信息
        /// </summary>
        private List<string[]> _logInfo = new List<string[]>();
        /// <summary>
        /// 写日志线程
        /// </summary>
        Thread _threadWriteLog = null;

        #endregion

        #region 对外方法

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="exc">错误</param>
        /// <param name="fileName">try...catch 所在页面</param>
        public void WriteErrorLog(Exception exc, string fileName)
        {
            string[] log = GetErrorLogInfo(exc, fileName);
            this._logInfo.Add(log);
        }

        /// <summary>
        /// 记录常规日志
        /// </summary>
        /// <param name="message">日志信息</param>
        public void WriteRoutineLog(string message)
        {
            string[] log = GetRoutineLog(message);
            this._logInfo.Add(log);
        }

        #endregion

        #region 对内方法

        /// <summary>
        /// 记录日志
        /// </summary>
        private void WriteLog()
        {
            while (true)
            {
                Thread.Sleep(200);
                if (_logInfo.Count > 0)
                {
                    string[] info = _logInfo[0];
                    WriteLog(info, this.LogPath, this.LogName);
                    this._logInfo.RemoveAt(0);             
                }
            }
        }

        /// <summary>
        /// 得到异常信息的字符串数组
        /// </summary>
        /// <param name="exc">异常对象</param>
        /// <returns>字符串数组</returns>
        private string[] GetErrorLogInfo(Exception exc, string fileName)
        {
            string[] info = new string[7];
            info[0] = string.Format("记录时间:{0}", DateTime.Now.ToString("yyyy-mm-dd hh:mm:ss"));
            info[1] = string.Format("异常实例:{0}", exc.InnerException != null ? exc.InnerException.ToString() : string.Empty);
            info[2] = string.Format("try..catch所在页面:{0}", fileName);
            info[3] = string.Format("引发异常的方法:{0}", exc.TargetSite.ToString());
            info[4] = string.Format("导致错误的应用程序或对象的名称:{0}", exc.Source);
            info[5] = string.Format("错误信息:{0}", exc.Message);
            info[6] = string.Empty;
            return info;
        }

        /// <summary>
        /// 得到常规日志记录
        /// </summary>
        /// <param name="message">日志信息</param>
        private string[] GetRoutineLog(string message)
        {
            string[] log = new string[3];
            log[0] = string.Format("记录时间:{0}", DateTime.Now.ToString("yyyy-mm-dd hh:mm:ss"));
            log[1] = string.Format("记录信息:{0}", message);
            log[2] = string.Empty;
            return log;
        }

        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="log">日志信息</param>
        /// <param name="path">日志路径</param>
        /// <param name="logName">日志名称</param>
        private void WriteLog(string[] log, string path, string logName)
        {
            string fullName = string.Format(@"{0}\{1}", path.TrimEnd('\\'), logName);
            if (!File.Exists(fullName))
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                using (FileStream fs = new FileStream(fullName, FileMode.Create))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        for (int i = 0; i < log.Length; i++)
                        {
                            sw.WriteLine(log[i]);
                        }
                    }
                }
            }
            else
            {
                using (FileStream fs = new FileStream(fullName, FileMode.Append))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        for (int i = 0; i < log.Length; i++)
                        {
                            sw.WriteLine(log[i]);
                        }
                    }
                }
            }
        }

        #endregion
    }

 

posted on 2013-11-12 10:50  tyler  阅读(264)  评论(0编辑  收藏  举报