日志操作封装

/*************************************************
 * 描述:本地日志操作类
 * 功能:1、本地常规日志写操作。
 *           2、本地异常日志写操作。
 *           3、本地日志查询操作。
 * 
 * Author :Y
 * Date:
 * Update:
 * ************************************************/

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

namespace CoreX.Common
{
    /// <summary>
    /// 本地日志操作类
    /// </summary>
    public class LocalLog
    {
        //本地日志根目录
        private static string logRootPath = null;
        //本地日志级别
        private static LogLevel logLevel = LogLevel.easy | LogLevel.common | LogLevel.important | LogLevel.emergency;
        //日志文件最大大小
        private const long MAXSIZE = 1048576;
        private static readonly object lockObj = new object();

        //获取本地日志根目录
        private static string RootPath
        {
            get
            {
                if (string.IsNullOrEmpty(logRootPath))
                {
                    logRootPath = ConfigurationManager.AppSettings["LocalLogPath"];
                    if (string.IsNullOrEmpty(logRootPath))
                    {
                        logRootPath = AppDomain.CurrentDomain.BaseDirectory + @"\Log\";
                    }
                }

                return logRootPath;
            }
        }
        //本地日志级别
        private static LogLevel Level
        {
            get
            {
                string level = ConfigurationManager.AppSettings["LogLevel"];
                int levelNum = (int)logLevel;
                if (int.TryParse(level, out levelNum))
                {
                    logLevel = (LogLevel)levelNum;
                }
                return logLevel;
            }
        }
        //当前日志文件
        private static string LogFile
        {
            get
            {
                string logPath = RootPath;
                if (!Directory.Exists(logPath))
                {
                    Directory.CreateDirectory(logPath);
                }
//#if DEBUG
//                string logFile = Path.Combine(logPath, $"{DateTime.Today.ToString("yyyyMMdd")}.log");
//#else
                string date = DateTime.Today.ToString("yyyyMMdd_");
                string[] logFiles = Directory.GetFiles(logPath, date + "*.log", SearchOption.TopDirectoryOnly);
                string logFile = string.Empty;
                if (logFiles.Length == 0)
                {
                    logFile = Path.Combine(logPath, date + "1.log");
                }
                else
                {
                    logFile = Path.Combine(logPath, date + logFiles.Length + ".log");
                }
                FileInfo fileInfo = new FileInfo(logFile);
                if (fileInfo.Exists && fileInfo.Length > MAXSIZE)
                {
                    logFile = Path.Combine(logPath, date + (logFiles.Length + 1) + ".log");
                }
//#endif

                return logFile;
            }
        }
        
        //错误日志文件
        private static string ErrLogFile
        {
            get
            {
                string logPath = RootPath;
                if (!Directory.Exists(logPath))
                {
                    Directory.CreateDirectory(logPath);
                }
                //#if DEBUG
                //                string logFile = Path.Combine(logPath, $"{DateTime.Today.ToString("yyyyMMdd")}.log");
                //#else
                string date = DateTime.Today.ToString("yyyyMMdd.err_");
                string[] logFiles = Directory.GetFiles(logPath, date + "*.log", SearchOption.TopDirectoryOnly);
                string logFile = string.Empty;
                if (logFiles.Length == 0)
                {
                    logFile = Path.Combine(logPath, date + "1.log");
                }
                else
                {
                    logFile = Path.Combine(logPath, date + logFiles.Length + ".log");
                }
                FileInfo fileInfo = new FileInfo(logFile);
                if (fileInfo.Exists && fileInfo.Length > MAXSIZE)
                {
                    logFile = Path.Combine(logPath, date + (logFiles.Length + 1) + ".log");
                }
                //#endif

                return logFile;
            }
        }

        /// <summary>
        /// 写本地日志
        /// </summary>
        /// <param name="logLevel">日志级别</param>
        /// <param name="log">日志内容</param>
        public static void Write(LogLevel logLevel, string log)
        {
            if ((Level & logLevel) == logLevel && !string.IsNullOrEmpty(log))
            {
                lock (lockObj)
                {
                    try
                    {
                        using(StreamWriter writer = new StreamWriter(LogFile, true, Encoding.GetEncoding("gb2312")))
                        {
                            writer.WriteLine(">{0}\t{1}", DateTime.Now.ToString("HH:mm:ss.ffff"), log);
                        }
                    }
                    catch(Exception ex)
                    {
#if DEBUG
                        string exceptionFile = Path.Combine(RootPath, "exception.log");
                        try
                        {
                            using(StreamWriter writer =
                            new StreamWriter(exceptionFile, true, Encoding.GetEncoding("gb2312")))
                            {
                                writer.WriteLine("{0}{1}", ex.Message, Environment.NewLine);
                            }
                        }
                        finally
                        {
                            throw ex;
                        }
#endif
                    }

                    if(logLevel == LogLevel.important || logLevel == LogLevel.emergency)
                    {
                        try
                        {
                            using(StreamWriter writer = new StreamWriter(ErrLogFile, true, Encoding.GetEncoding("gb2312")))
                            {
                                writer.WriteLine(">{0}\t{1}", DateTime.Now.ToString("HH:mm:ss.ffff"), log);
                            }
                        }
                        catch(Exception ex)
                        {
#if DEBUG
                            string exceptionFile = Path.Combine(RootPath, "exception.log");
                            try
                            {
                                using(StreamWriter writer =
                                new StreamWriter(exceptionFile, true, Encoding.GetEncoding("gb2312")))
                                {
                                    writer.WriteLine("{0}{1}", ex.Message, Environment.NewLine);
                                }
                            }
                            finally
                            {
                                throw ex;
                            }
#endif
                        }
                    }
                }
            }
            WriteShell(log, false);
        }
        /// <summary>
        /// 写本地日志
        /// </summary>
        /// <param name="logLevel">日志级别</param>
        /// <param name="logFormat">带复合格式的日志内容</param>
        /// <param name="args">复合格式参数</param>
        public static void Write(LogLevel logLevel, string logFormat, params object[] args)
        {
            string log = string.Format(logFormat, args);
            Write(logLevel, log);
            WriteShell(log, false);
        }
        /// <summary>
        /// 写本地异常日志
        /// </summary>
        /// <param name="ex">异常对象</param>
        /// <param name="logFormat">带复合格式的日志内容</param>
        /// <param name="args">复合格式参数</param>
        public static void Write(Exception ex, string logFormat, params object[] args)
        {
            string log = string.Format(logFormat, args);
            if (!string.IsNullOrEmpty(log))
            {
                log += Environment.NewLine;
            }
            log += string.Format("{0}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace);
            if ((Level & LogLevel.important) == LogLevel.important && !string.IsNullOrEmpty(log))
            {
                lock (lockObj)
                {
                    try
                    {
                        using (StreamWriter writer = new StreamWriter(LogFile, true, Encoding.GetEncoding("gb2312")))
                        {
                            writer.WriteLine(">{0}\t{1}", DateTime.Now.ToString("HH:mm:ss.ffff"), log);
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                    //写到错误日志文件
                    try
                    {
                        using (StreamWriter writer = new StreamWriter(ErrLogFile, true, Encoding.GetEncoding("gb2312")))
                        {
                            writer.WriteLine(">{0}\t{1}", DateTime.Now.ToString("HH:mm:ss.ffff"), log);
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                }
            }
            WriteShell(log, true);
        }

        //日志信息写到控制台
        private static void WriteShell(string output, bool isException)
        {
#if DEBUG_Console
            if (!string.IsNullOrEmpty(output))
            {
                if (!shellOpened)
                {
                    AllocConsole();
                    Console.Title = "日志信息跟踪";
                    Console.BackgroundColor = ConsoleColor.White;
                    shellOpened = true;
                }
                Console.ForegroundColor = ConsoleColor.Black;
                Console.Write("{0}[{1}]->", DateTime.Now.ToString("HH:mm:ss.fffff"), output == null ? 0 : output.Length);
                if (isException)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                }
                Console.WriteLine(output);
            }
#endif
        }
#if DEBUG_Console
        public static void WriteShell(string output)
        {
            WriteShell(output, false);
        }
        public static void WriteShell(string format, params object[] args)
        {
            WriteShell(string.Format(format, args), false);
        }
        public static void WriteShell(string output, Exception ex)
        {
            WriteShell(string.Format("{0}{1}{2}{1}{3}", output, Environment.NewLine, ex.Message, ex.StackTrace), true);
        }

        //控制台窗口是否弹出
        private static bool shellOpened = false;
        //弹出控制台窗口
        [System.Runtime.InteropServices.DllImport("kernel32.dll")]
        private static extern Boolean AllocConsole();
        //释放控制台窗口
        [System.Runtime.InteropServices.DllImport("kernel32.dll")]
        private static extern Boolean FreeConsole();
#endif
    }

    /// <summary>
    /// 日志级别枚举
    /// </summary>
    [Flags]
    public enum LogLevel : int
    {
        /// <summary>
        /// 不重要=1
        /// </summary>
        easy = 1,
        /// <summary>
        /// 一般=2
        /// </summary>
        common = 2,
        /// <summary>
        /// 重要=4
        /// </summary>
        important = 4,
        /// <summary>
        /// 急=8
        /// </summary>
        emergency = 8
    }
}

 

posted @ 2020-05-28 20:45  博客YS  阅读(8)  评论(0编辑  收藏  举报