给系统添加日志(封装成了日志类,其它应用可以直接调用)

给系统添加日志后,在系统出错时,可以通过日志查看请求的接口,向接口发送的数据,以及接口数返回的数据,请求时花费的时间,方便排查问题。

1.日志类

WMSLog.cs

 /// <summary>
    /// 日志类
    /// </summary>
    public class WMSLog
    {
        //日志文件所在路径
        private static string _logPath = "";
        /// <summary>
        /// 保存日志的文件夹
        /// </summary>
        public static string LogPath
        {
            get
            {
                if (_logPath == string.Empty)
                {
                    if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + @"WMSLog\"))
                    {
                        Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + @"WMSLog\");
                    }

                    _logPath = AppDomain.CurrentDomain.BaseDirectory + @"WMSLog\";
                }
                return _logPath;
            }
        }
        //日志前缀说明信息
        private static string LogFielPrefix = "WMS";

        private static string FilePath = string.Empty;//未加密的文件路径
        private static string EFilePath = string.Empty;//加密后的文件路径
        /// <summary>
        /// 写日志
        /// <param name="logType">日志类型</param>
        /// <param name="msg">日志内容</param> 
        /// </summary>
        private static void WriteLog(string logType, string msg)
        {
            //先检测日志文件是否存在,不存在则创建
            CheckFileExist();

            string filename = string.Format("{0}_{1}.Log", LogFielPrefix, DateTime.Now.ToString("yyyy-MM-dd"));
            FilePath = string.Format("{0}{1}", LogPath, filename);
            EFilePath = string.Format("{0}/Encrypt{1}", LogPath, filename);

            //开始写入日志
            StreamWriter sw = null;//未加密的
            StreamWriter esw = null;//加密的
            string tempMsg = string.Format("{0}#{1}:{2}", logType, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"), msg);

            #region 未加密的日志写入
            try
            {
                //同一天同一类日志以追加形式保存
                sw = File.AppendText(FilePath);

                //写入日志
                sw.WriteLine(tempMsg);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                if (sw != null) sw.Close();
            }
            #endregion

            #region 加密的日志写入
            try
            {
                //同一天同一类日志以追加形式保存
                esw = File.AppendText(EFilePath);

                //对字符串进行加密
                string enMsg = EncryptString(tempMsg);

                //写入日志
                esw.WriteLine(enMsg);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                if (esw != null) esw.Close();
            }
            #endregion
        }

        /// <summary>
        /// 检测日志文件是否存在,不存在则创建
        /// </summary>
        private static void CheckFileExist()
        {
            string filename = string.Format("{0}_{1}.Log", LogFielPrefix, DateTime.Now.ToString("yyyy-MM-dd"));
            FilePath = string.Format("{0}{1}", LogPath, filename);
            EFilePath = string.Format("{0}/Encrypt{1}", LogPath, filename);

            //未加密的文件如果不存在则创建
            if (!File.Exists(FilePath))
            {
                using (File.Create(FilePath))
                {
                    File.SetAttributes(FilePath, FileAttributes.Normal);
                    FileAttributes myAttributes = File.GetAttributes(FilePath);
                    File.SetAttributes(FilePath, myAttributes | FileAttributes.System);
                    myAttributes = File.GetAttributes(FilePath);
                    File.SetAttributes(FilePath, myAttributes | FileAttributes.Hidden);
                    myAttributes = File.GetAttributes(FilePath);
                    File.SetAttributes(FilePath, myAttributes | FileAttributes.Archive);
                    File.GetAttributes(FilePath);
                }
            }

            //加密的文件如果不存在则创建
            if (!File.Exists(EFilePath))
            {
                FileStream fs = File.Create(EFilePath);
                fs.Close();
            }
        }

        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="oldMsg"></param>
        /// <returns></returns>
        private static string EncryptString(string oldMsg)
        {
            try
            {
                string enKey = "99999999";
                string enIV = "88888888";
                string enSourceString = EncryptClass.Encrypt(oldMsg, enKey, enIV);
                return enSourceString;
            }
            catch (Exception ex)
            {
                return string.Format("日志加密出错,只能打印加密报的错:{0}", ex.Message);
            }

        }

        /// <summary>
        /// 写日志
        /// </summary>
        public static void WriteLog(LogType logType, string msg)
        {
            WriteLog(logType.ToString(), msg);
        }
    }
    /// <summary>
    /// 日志类型
    /// </summary>
    public enum LogType
    {
        Trace,  //堆栈跟踪信息
        Warning,//警告信息
        Error,  //错误信息应该包含对象名、发生错误点所在的方法名称、具体错误信息
        SQL    //与数据库相关的信息
    }

    public class EncryptClass
    {
        public static string Encrypt(string sourceString, string key, string iv)
        {
            try
            {
                byte[] btKey = Encoding.UTF8.GetBytes(key);
                byte[] btIV = Encoding.UTF8.GetBytes(iv);
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                using (MemoryStream ms = new MemoryStream())
                {
                    byte[] inData = Encoding.UTF8.GetBytes(sourceString);
                    try
                    {
                        using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
                        {
                            cs.Write(inData, 0, inData.Length);
                            cs.FlushFinalBlock();
                        }
                        return Convert.ToBase64String(ms.ToArray());
                    }
                    catch
                    {
                        return sourceString;
                    }
                }
            }
            catch
            {

            }
            return "DES加密出错!";
        }

        public static string Decrypt(string encryptedString, string key, string iv)
        {
            byte[] btKey = Encoding.UTF8.GetBytes(key);
            byte[] btIV = Encoding.UTF8.GetBytes(iv);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            using (MemoryStream ms = new MemoryStream())
            {
                byte[] inData = Convert.FromBase64String(encryptedString);
                try
                {
                    using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
                    {
                        cs.Write(inData, 0, inData.Length);
                        cs.FlushFinalBlock();
                    }
                    return Encoding.UTF8.GetString(ms.ToArray());
                }
                catch
                {
                    return encryptedString;
                }
            }
        }
    }

 

2.使用

(1)WMSLog.WriteLog(LogType.Trace, string.Format("发送的数据:cmd:{0};  json:{1}", pacSend.cmd, GetRequestJson()));

pacSend.cmd:协议命令字

GetRequestJson():发送的数据

 

 (2)Stopwatch  用来记录网络请求耗时

Stopwatch timeWatch = new Stopwatch();

timeWatch.Start();
WMSLog.WriteLog(LogType.Trace, string.Format("{0}开始网络请求", pacSend.cmd));
timeWatch.Stop();
long watchTime = timeWatch.ElapsedMilliseconds;
WMSLog.WriteLog(LogType.Trace, string.Format("{0}请求耗时:{1} ms", pacSend.cmd, watchTime.ToString()));

(3) WMSLog.WriteLog(LogType.Trace, string.Format("服务端返回的数据:cmd:{0};  json:{1}", pacSend.cmd, GetResponseJson()));

(4)Warning类型,多放在try catch中

WMSLog.WriteLog(LogType.Warning, "下载模板失败");

(5)Error类型错误,多放在try catch中

 WMSLog.WriteLog(LogType.Error, string.Format("检查网络连接状态:{0}", e.ToString()));

 

posted @ 2022-03-14 18:01  MrKing&  阅读(173)  评论(0编辑  收藏  举报