C#日志操作类

using System;
using System.Collections.Generic;
using System.Web;
using System.Threading;
using System.IO;
using System.Text.RegularExpressions;

namespace XiaoFeng
{
    /// <summary>
    /// 日志操作类
    /// Email : jacky@zhuovi.com
    /// QQ : 7092734
    /// Site : www.zhuovi.com
    /// Version : 2.0
    /// Update Date : 2018-03-15
    /// </summary>
    public static class LogHelper
    {
        #region 构造器
        /// <summary>
        /// 构造器
        /// </summary>
        static LogHelper()
        {
            /*初始化数据*/
            ThreadPool.SetMaxThreads(30, 30);
            ThreadPool.SetMinThreads(1, 1);
            /*是否写日志*/
            string isLog = Config.GetConfig("Log");
            IsWriteLog = isLog != "0";
            if (!IsWriteLog) return;
            /*路径*/
            if (LogPath == "")
            {
                LogPath = Config.GetConfig("LogPath");
                if (LogPath.IsNullOrEmpty()) LogPath = "Log";
                LogPath = System.AppDomain.CurrentDomain.BaseDirectory + LogPath + "\\";
            }
            if (!Directory.Exists(LogPath)) Directory.CreateDirectory(LogPath);
        }
        #endregion

        #region 属性
        /// <summary>
        /// 日志保存路径
        /// </summary>
        private static string LogPath = "";
        /// <summary>
        /// 文件锁
        /// </summary>
        private static readonly object FileLock = new object();
        /// <summary>
        /// 是否写日志
        /// </summary>
        private static Boolean IsWriteLog = true;
        /// <summary>
        /// 计时器
        /// </summary>
        private static int Count = 0;
        #endregion

        #region 方法

        #region 记录日志
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="logData">日志对象</param>
        public static void WriteLog(LogData logData)
        {
            if (!IsWriteLog) return;
            ThreadPool.QueueUserWorkItem((o) =>
            {
                Thread.CurrentThread.IsBackground = true;
                Run(logData);
            });
        }
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="logType">日志类型</param>
        /// <param name="DataSource">日志源</param>
        /// <param name="ClassName">日志类名</param>
        /// <param name="FunctionName">方法名</param>
        /// <param name="Message">日志信息</param>
        public static void WriteLog(LogType logType, string DataSource, string ClassName, string FunctionName, string Message)
        {
            WriteLog(new LogData
            {
                logType = logType,
                DataSource = DataSource,
                ClassName = ClassName,
                FunctionName = FunctionName,
                Message = Message
            });
        }
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="logType">日志类型</param>
        /// <param name="Message">日志信息</param>
        public static void WriteLog(LogType logType, string Message)
        {
            WriteLog(new LogData
            {
                logType = logType,
                Message = Message
            });
        }
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="Message">日志信息</param>
        public static void WriteLog(string Message)
        {
            WriteLog(new LogData
            {
                logType = LogType.Info,
                Message = Message
            });
        }
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="ex">错误信息</param>
        /// <param name="Message">信息</param>
        public static void WriteLog(System.Exception ex, string Message = "")
        {
            WriteLog(new LogData
            {
                logType = LogType.Error,
                Message = ex.Message,
                DataSource = ex.Source,
                ClassName = ex.TargetSite.DeclaringType.Name,
                FunctionName = ex.TargetSite.Name,
                StackTrace = ex.StackTrace + (String.IsNullOrEmpty(Message) ? "" : ("\r\n" + Message))
            });
        }
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="ex">错误信息</param>
        /// <param name="Message">信息</param>
        public static void Error(Exception ex, string Message = "") { WriteLog(ex, Message); }
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="Message">信息</param>
        public static void Info(string Message) { WriteLog(LogType.Info, Message); }
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="Message">信息</param>
        public static void Debug(string Message) { WriteLog(LogType.Debug, Message); }
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="Message">信息</param>
        public static void SQL(string Message) { WriteLog(LogType.SQL, Message); }
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="Message">信息</param>
        public static void Warn(string Message) { WriteLog(LogType.Warn, Message); }

        #endregion

        #region 文件是否存在
        /// <summary>
        /// 文件是否存在
        /// </summary>
        /// <param name="FilePath">文件路径</param>
        private static void ExistsFile(string FilePath)
        {
            if (!File.Exists(FilePath))
            {
                FileStream fso = File.Create(FilePath);
                fso.Close();
                fso.Dispose();

                StreamWriter SW = File.AppendText(FilePath);
                SW.WriteLine("┏━━━━━━━━━━━━━━━━━━━━━━━━━┓");
                SW.WriteLine("┃                应用日志文件  v3.0                ┃");
                SW.WriteLine("┣━━━━━━━━━━━━━━━━━━━━━━━━━┫");
                SW.WriteLine("┃         公司 : 卓伟软件(www.zhuovi.com)          ┃");
                SW.WriteLine("┃         作者 : jacky                             ┃");
                SW.WriteLine("┃           QQ : 7092734                           ┃");
                SW.WriteLine("┃        Email : jacky@zhuovi.com                  ┃");
                SW.WriteLine("┃     创建时间 : {0}           ┃".format(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")));
                SW.WriteLine("┗━━━━━━━━━━━━━━━━━━━━━━━━━┛");
                SW.WriteLine("");
                SW.Flush();
                SW.Close();
                SW.Dispose();
            }
        }
        #endregion

        #region 写日志
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="logData">日志数据</param>
        /// <param name="logPath">日志路径</param>
        public static void Run(LogData logData, string logPath = null)
        {
            try
            {
                logPath = logPath ?? LogPath;
                if (logPath.IsNullOrEmpty())
                    logPath = LogPath;
                else
                {
                    logPath = logPath.RemovePattern(@"[\\/]+$");
                    if (!logPath.isBasePath())
                        logPath = System.AppDomain.CurrentDomain.BaseDirectory + logPath.Replace("/", "\\") + "\\";
                    if (!Directory.Exists(logPath)) Directory.CreateDirectory(logPath);
                }
                Monitor.Enter(FileLock);
                string FilePath = logPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
                ExistsFile(FilePath);
                StreamWriter sw = File.AppendText(FilePath);
                if (logData.logType == LogType.Error)
                {
                    sw.WriteLine("".PadLeft(70, '='));
                    sw.WriteLine("日志时间 : [{0}]  ".format(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")));
                    sw.WriteLine("日志类型 : {0}\t线 程 ID : {1}"
                        .format(logData.logType.ToString(), Thread.CurrentThread.ManagedThreadId));
                    if (logData.DataSource != null && logData.DataSource != "") sw.WriteLine("数 据 源 : " + logData.DataSource);
                    if (logData.ClassName != null && logData.ClassName != "") sw.WriteLine("方法所属类 : " + logData.ClassName);
                    if (logData.FunctionName != null && logData.FunctionName != "") sw.WriteLine("方 法 名 : " + logData.FunctionName);

                    sw.WriteLine("日志信息 : " + (logData.isReplace ? logData.Message.RemovePattern(@"(\w+_)") : logData.Message));
                    sw.WriteLine("日志堆栈 : " + logData.StackTrace);
                }
                else if (logData.logType == LogType.Info || logData.logType == LogType.Debug || logData.logType == LogType.Warn || logData.logType == LogType.SQL)
                {
                    sw.WriteLine("".PadLeft(70, '-'));
                    sw.WriteLine("日志时间 : [{0}]\t日志类型:{1}\t线 程 ID : {2}\r\n{3}".format(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), logData.logType.ToString(), Thread.CurrentThread.ManagedThreadId, logData.Message));
                }
                sw.Flush();
                sw.Close();
                sw.Dispose();
                Monitor.Exit(FileLock);
            }
            catch
            {
                if (Interlocked.Increment(ref Count) == 3)
                {
                    Count = 0;
                    return;
                }
                Run(logData);
            }
        }
        #endregion

        #endregion

        #region 枚举
        /// <summary>
        /// 错误类型
        /// </summary>
        public enum LogType
        {
            /// <summary>
            /// 信息
            /// </summary>
            Info = 0,
            /// <summary>
            /// 警告
            /// </summary>
            Warn = 1,
            /// <summary>
            /// 出错
            /// </summary>
            Error = 2,
            /// <summary>
            /// SQL
            /// </summary>
            SQL = 3,
            /// <summary>
            /// bug
            /// </summary>
            Debug = 4
        }
        #endregion

        #region 结构体
        /// <summary>
        /// 日志结构体
        /// </summary>
        public struct LogData
        {
            /// <summary>
            /// 错误ID
            /// </summary>
            public string ErrorID;
            /// <summary>
            /// 方法名
            /// </summary>
            public string FunctionName;
            /// <summary>
            /// 类名
            /// </summary>
            public string ClassName;
            /// <summary>
            /// 信息
            /// </summary>
            public string Message;
            /// <summary>
            /// 错误源
            /// </summary>
            public string DataSource;
            /// <summary>
            /// 日志类型
            /// </summary>
            public LogType logType;
            /// <summary>
            /// 是否去除前缀
            /// </summary>
            public Boolean isReplace;
            /// <summary>
            /// 错误堆栈
            /// </summary>
            public string StackTrace;
        }
        #endregion
    }
}
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值