using System;
using System.IO;
using System.Text;

namespace ZB.QueueSys.Common
{
    public class LogHelper
    {
        //private static LogHelper instance;
        //public static LogHelper Instance
        //{
        //    get
        //    {
        //        if (instance == null) instance = new LogHelper();
        //        return LogHelper.instance;
        //    }
        //}

        //定义一个用于保存静态变量的实例
        private static LogHelper instance = null;
        //定义一个保证线程同步的标识
        private static readonly object locker = new object();
        //构造函数为私有,使外界不能创建该类的实例
        private LogHelper() { }
        public static LogHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (locker)
                    {
                        if (instance == null) instance = new LogHelper();
                    }
                }
                return instance;
            }
        }


        public static LogHelper Default = new LogHelper();
        public string OutputLog = PubVariable.Instance.IsUseLog;
        public const string DIAG = "Diag";
        public const string Enrol = "Enrol";

        public StringBuilder sb = new StringBuilder();
        public void WriteCacheLog(string msg)
        {
            sb.Append(DateTime.Now.ToString("HH:mm:ss") + ": " + msg + "\r\n");
        }

        public void SaveLogToTxt(string logFile)
        {
            bool isAppend = false;
            if (File.Exists(logFile))
            {
                //File.Delete(logFile);
                isAppend = true;
            }

            using (StreamWriter sw = new StreamWriter(logFile, isAppend))
            {
                sw.WriteLine(sb.ToString());
                sw.Flush();
                sw.Close();
            }
        }
        /// <summary>
        /// 保存并输出日志
        /// </summary>
        /// <param name="WriteTxt"></param>
        /// <param name="isOutPut">0、不输出</param>
        public void SaveTextAndOutPut(string WriteTxt, string isOutPut)
        {
            try
            {
                if (isOutPut == "0") return;
                string LogPath = "C:\\ZB.QueueSys\\TempLog\\";
                LogPath = PubVariable.Instance.LogFilePath;
                if (!Directory.Exists(LogPath))
                {
                    Directory.CreateDirectory(LogPath);
                }

                LogPath += System.DateTime.Now.ToString("yyyyMMdd");
                if (!Directory.Exists(LogPath))
                {
                    Directory.CreateDirectory(LogPath);
                }
                //创建一个文件流,用以写入或者创建一个StreamWriter
                FileStream fs = new FileStream(LogPath + "\\D" + System.DateTime.Now.Hour.ToString() + ".txt", FileMode.OpenOrCreate, FileAccess.Write);
                StreamWriter m_streamWriter = new StreamWriter(fs);
                m_streamWriter.Flush();

                // 使用StreamWriter来往文件中写入内容
                m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
                // 把richTextBox1中的内容写入文件
                m_streamWriter.WriteLine(DateTime.Now.ToString("HH:mm:ss") + ": \n\r" + WriteTxt);
                //关闭此文件
                m_streamWriter.Flush();
                m_streamWriter.Close();
            }
            catch
            {
            }
        }

        public void SaveText(string WriteTxt)
        {
            try
            {
                if (OutputLog == "0") return;
                string LogPath = "C:\\ZB.QueueSys\\TempLog\\";
                LogPath = PubVariable.Instance.LogFilePath;
                if (!Directory.Exists(LogPath))
                {
                    Directory.CreateDirectory(LogPath);
                }

                LogPath += System.DateTime.Now.ToString("yyyyMMdd");
                if (!Directory.Exists(LogPath))
                {
                    Directory.CreateDirectory(LogPath);
                }
                //创建一个文件流,用以写入或者创建一个StreamWriter
                FileStream fs = new FileStream(LogPath + "\\D" + System.DateTime.Now.Hour.ToString() + ".txt", FileMode.OpenOrCreate, FileAccess.Write);
                StreamWriter m_streamWriter = new StreamWriter(fs);
                m_streamWriter.Flush();

                // 使用StreamWriter来往文件中写入内容
                m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
                // 把richTextBox1中的内容写入文件
                m_streamWriter.WriteLine(DateTime.Now.ToString("HH:mm:ss") + ": \n\r" + WriteTxt);
                //关闭此文件
                m_streamWriter.Flush();
                m_streamWriter.Close();
            }
            catch
            {
            }
        }

        public void SaveAsText(string WriteTxt)
        {
            try
            {
                string LogPath = "C:\\Temp\\Diag\\";
                if (!Directory.Exists(LogPath)) return; //作为开关用

                LogPath += System.DateTime.Now.ToString("yyyyMMdd");
                if (!Directory.Exists(LogPath)) Directory.CreateDirectory(LogPath);
                //创建一个文件流,用以写入或者创建一个StreamWriter
                FileStream fs = new FileStream(LogPath + "\\D" + System.DateTime.Now.Hour.ToString() + ".txt", FileMode.OpenOrCreate, FileAccess.Write);
                StreamWriter m_streamWriter = new StreamWriter(fs);
                m_streamWriter.Flush();

                // 使用StreamWriter来往文件中写入内容
                m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
                // 把richTextBox1中的内容写入文件
                m_streamWriter.WriteLine(DateTime.Now.ToString("HH:mm:ss") + ": " + WriteTxt);
                //关闭此文件
                m_streamWriter.Flush();
                m_streamWriter.Close();
            }
            catch
            {
            }
        }

        public void SaveAsText(string WriteTxt, string Studyid)
        {
            try
            {
                string LogPath = "C:\\Temp\\DIAG\\";
                if (!Directory.Exists(LogPath)) return; //作为开关用

                LogPath = LogPath + System.DateTime.Now.ToString("yyyyMMdd");
                if (!Directory.Exists(LogPath)) Directory.CreateDirectory(LogPath);

                if (string.IsNullOrEmpty(Studyid)) Studyid = "1000";
                string filename = LogPath + "\\" + Studyid + ".txt";

                //创建一个文件流,用以写入或者创建一个StreamWriter
                FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write);
                StreamWriter m_streamWriter = new StreamWriter(fs);
                m_streamWriter.Flush();

                // 使用StreamWriter来往文件中写入内容
                m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
                // 把richTextBox1中的内容写入文件
                m_streamWriter.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff") + ": " + WriteTxt);
                //关闭此文件
                m_streamWriter.Flush();
                m_streamWriter.Close();
            }
            catch
            {
            }
        }
    }

    public class MyLogHelper
    {
        /// <summary>
        /// 信息类型
        /// </summary>
        public enum LogLevel
        {
            /// <summary>
            /// 普通信息
            /// </summary>
            Info,
            /// <summary>
            /// 错误
            /// </summary>
            Error
        }

        /// <summary>
        /// 普通信息写入日志
        /// </summary>
        /// <param name="message"></param>
        /// <param name="logType"></param>
        public static void Info(string message, LogType logType = LogType.Overall)
        {
            if (string.IsNullOrEmpty(message)) return;
            var path = string.Format(@"\{0}\", logType.ToString());
            WriteLog(path, "", message);
        }
        /// <summary>
        /// 自定义错误信息写入
        /// </summary>
        /// <param name="message">自定义消息</param>
        /// <param name="logType">存储目录类型</param>
        public static void Error(string message, LogType logType = LogType.Overall)
        {
            if (string.IsNullOrEmpty(message)) return;
            var path = string.Format(@"\{0}\", logType.ToString());
            WriteLog(path, "Error ", message);
        }
        /// <summary>
        /// 程序异常信息写入
        /// </summary>
        /// <param name="e">异常</param>
        /// <param name="logType">存储目录类型</param>
        public static void Error(Exception e, LogType logType = LogType.Overall)
        {
            if (e == null) return;
            var path = string.Format(@"\{0}\", logType.ToString());
            WriteLog(path, "Error ", e.Message);
        }
        /// <summary>
        /// 写日志的最终执行动作
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="prefix">前缀</param>
        /// <param name="message">内容</param>
        public static void WriteLog(string path, string prefix, string message)
        {
            path = @"C:\RisLog\";

            if (!Directory.Exists(path)) Directory.CreateDirectory(path);

            var fileName = string.Format("{0}{1}.Log", prefix, DateTime.Now.ToString("yyyy-MM-dd"));
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);

            using (FileStream fs = new FileStream(path + fileName, FileMode.Append, FileAccess.Write, FileShare.Write, 1024, FileOptions.Asynchronous))
            {
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(DateTime.Now.ToString("HH:mm:ss") + " " + message + "\r\n");
                IAsyncResult writeResult = fs.BeginWrite(buffer, 0, buffer.Length,
                    (asyncResult) =>
                    {
                        var fStream = (FileStream)asyncResult.AsyncState;
                        fStream.EndWrite(asyncResult);
                    },

                    fs);
                fs.Close();
            }
        }
    }

    /// <summary>
    /// 日志文件存放文件夹分类枚举
    /// </summary>
    public enum LogType
    {
        /// <summary>
        /// 普通信息
        /// </summary>
        Info,
        /// <summary>
        /// 错误
        /// </summary>
        Error,
        /// <summary>
        /// 其他全部信息
        /// </summary>
        Overall,
    }

}

  

原文地址:http://www.cnblogs.com/YYkun/p/16836997.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性