c#日志保存类,自动删除旧日志,只保存一个月内


    class LogHelper
    {
        static Dictionary<string, object> objLook = new Dictionary<string, object>();
        public static string m_Path = "LogMsg";//根目录的日志文件夹

        public static void WriteServerLog(Exception ex, string Message = "")
        {
            string _Path = "ServerLog";//单个功能的日志文件夹
            bool aa = objLook.ContainsKey(_Path);
            if (!objLook.ContainsKey(_Path))
            {
                objLook.Add(_Path, new object());
            }
            lock (objLook[_Path])
            {
                string MonthNow = DateTime.Now.Month.ToString();
                string DayNow = DateTime.Now.Day.ToString();
                if (DateTime.Now.Month < 10)
                {
                    MonthNow = "0" + MonthNow;
                }

                if (DateTime.Now.Day < 10)
                {
                    DayNow = "0" + DayNow;
                }
                string LogAddress = AppDomain.CurrentDomain.BaseDirectory + m_Path + @"\" + _Path + @"\";
                if (!System.IO.Directory.Exists(LogAddress))
                {
                    Directory.CreateDirectory(LogAddress);
                }
                string LogAddress2 = LogAddress +
                    DateTime.Now.Year + '-' +
                    MonthNow + '-' +
                    DayNow + _Path + ".log";

                //把异常信息输出到文件
                StreamWriter fs = new StreamWriter(LogAddress2, true);
                fs.WriteLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + ":" + Message);
                // fs.WriteLine(Message);
                if (ex != null)
                {
                    fs.WriteLine("异常信息:" + ex.Message);
                    fs.WriteLine("异常对象:" + ex.Source);
                    fs.WriteLine("调用堆栈:\n" + ex.StackTrace.ToString());
                    fs.WriteLine("触发方法:" + ex.TargetSite);
                }
                fs.Close();

                foreach (string str in Directory.GetFiles(LogAddress, "*.log", SearchOption.TopDirectoryOnly))
                {
                    if (!str.Contains(DateTime.Now.Year + "-" + MonthNow + "-"))
                    {
                        File.Delete(str);
                    }
                }

            }
        }
        
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值