zoukankan      html  css  js  c++  java
  • 日志帮助类

    从网上找了些资源,借鉴整理之后,自己随便写了一个。

        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
        }
  • 相关阅读:
    【git】git命令集合
    【maven】【IDEA】idea中使用maven编译项目,报错java: 错误: 找不到符号 【2】
    【mybatis】mybatis传参的几种方式
    【EasyExcel】使用easyExcel过程中,项目报错的解决集合
    【Maven】【IDEA】在idea中开发web项目,解决maven的jar包冲突的方法
    【Easyexcel】java导入导出超大数据量的xlsx文件 解决方法
    【maven】idea的pom文件修改,引入新的jar包,无效,本地仓库始终没有下载新jar包的问题解决【idea pom Dependency not found】
    【java】javac编译多个有依赖关系的java文件为class文件
    【java】javac命令在win10不可用,提示javac不是内部或外部命令,也不是可运行的程序【解决方法】
    【POI】java服务生成List数据集合,后台服务生成xlsx临时文件,并将临时文件上传到腾讯云上,并实现xlsx浏览器预览
  • 原文地址:https://www.cnblogs.com/rogation/p/3419055.html
Copyright © 2011-2022 走看看