使用log4net记录日志,会出现日志文件过大的问题。

下面是完整的日志类,开箱即用:

(1)制定日志路径;

(2)按日期记录文件;

(3)可限制文件大小;

(4)定期清理超过1个月(自定义)事件的日志;

(5)可跟踪记录日志是【哪个类】的【哪个方法】;

using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Text;
    using log4net;

    /// <summary>
    /// 日志记录类,log4net
    /// LOG文件夹,每个日期一个文件
    /// 默认最大100MB一个文件
    /// </summary>
    public class Loger
    {
        public Loger()
        {
            this.init();
        }

        private ILog loger;
        private string IsInfo;//是否记录info日志开关  2019-01-18
        private DateTime LastClearTime;
        public string logPath = "";
        private void init()
        {
            //下面两句应该放在网站刚刚启动时加载,并放在一个静态方法里方便调用
            
            log4net.Appender.RollingFileAppender appender = new log4net.Appender.RollingFileAppender();
            string maxFileSize = "";

            //读取配置文件,有配置固定目录的,使用固定目录
            try
            {
                string path = System.Configuration.ConfigurationSettings.AppSettings["NIS_LOG_PATH"];//日志文件存储路径
                maxFileSize = System.Configuration.ConfigurationSettings.AppSettings["NIS_LOG_FILE_SIZE"]; //日志文件大小 默认"10MB"一个;

                if (string.IsNullOrEmpty(path) == false)
                {
                    if (System.IO.Directory.Exists(path) == false)
                    {
                        System.IO.Directory.CreateDirectory(path);
                    }
                    appender.File = path;
                }
                else
                {
                    appender.File = "ErrorLog\\";
                }

                if(string.IsNullOrEmpty(maxFileSize))
                {
                    maxFileSize = "10MB";
                }
            }
            catch (Exception ex)
            {
                //System.Windows.Forms.MessageBox.Show("Log init erro:" + ex.Message + " " + ex.StackTrace);
                appender.File = "ErrorLog\\";
                
            }
            logPath = appender.File;

            appender.AppendToFile = true;
            appender.MaxSizeRollBackups =  -1;
            appender.MaximumFileSize = maxFileSize;  
            appender.RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Composite;//混合模式,即按日期,也按文件大小分隔
            appender.DatePattern = "NIS_yyyy-MM-dd\".txt\"";
            appender.StaticLogFileName = false;
            appender.LockingModel = new log4net.Appender.FileAppender.MinimalLock();
            appender.Layout = new log4net.Layout.PatternLayout("%d [%t] %-5p %c - (%line) %m%n");// "%date [%thread] %-5level - %message%newline");
            appender.ActivateOptions();

            log4net.Config.BasicConfigurator.Configure(appender);

            loger = LogManager.GetLogger("NIS");

            var rootAppender = ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository())
                                         .Root.Appenders.OfType<log4net.Appender.FileAppender>()
                                         .FirstOrDefault();

            logPath = rootAppender != null ? rootAppender.File : string.Empty;

            LastClearTime = DateTime.Now;
        }

        private string lastAssm = "";
        public void SaveLog(string info)
        {
            if (string.IsNullOrEmpty(this.IsInfo) == false && this.IsInfo.Equals("1"))
            {
                //为1则不记录  默认则记录
            }
            else
            {
                //记录谁调用
                string rt = "";

                //获取调用方法
                rt = GetMehtodTraceStr();

                if (lastAssm != rt)
                {
                    lastAssm = rt;
                    loger.Info(rt + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss,fff [1] INFO  - ") + info);
                }
                else
                {
                    loger.Info(info);
                }


                ClearLog();
            }
           
        }

        public void SaveExceptionLog(string info, Exception ex)
        {
            //记录谁调用
            string rt = "";

            //获取调用方法
            rt = JHNISCommonManage.GetInstance().GetMehtodTraceStr();

            if (lastAssm != rt)
            {
                lastAssm = rt;
                loger.Error(rt + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss,fff [1] INFO  - ") + info, ex);
            }
            else
            {
                loger.Error(info, ex);
            }

            loger.Error(rt + info, ex);
            ClearLog();
        }

        private void ClearLog()
        {
            try
            {
                if ((DateTime.Now - LastClearTime).TotalMinutes > 10)
                {
                    string path = logPath.Replace(logPath.Split('\\')[logPath.Split('\\').Length - 1], "");
                    string[] files = System.IO.Directory.GetFiles(path);
                    foreach (string f in files)
                    {
                        string date = f.Split('\\')[f.Split('\\').Length - 1];
                        date = date.Split('.')[0];
                        DateTime dtLog;
                        if (DateTime.TryParse(date, out dtLog))
                        {
                            if ((DateTime.Now - dtLog).TotalDays > 7)
                            {
                                try
                                {
                                    System.IO.File.Delete(f);
                                }
                                catch (Exception ex)
                                {

                                }
                            }
                        }
                    }
                    LastClearTime = DateTime.Now;
                }
            }
            catch (Exception ex)
            {
                //System.Windows.Forms.MessageBox.Show("ClearLog erro:" + ex.Message + " " + ex.StackTrace);
                SaveLog("清空历史日志失败:" + ex.Message);
            }

        }
    }

获取方法调用者(DLL类、方法名)

#region 获取方法调用者(DLL类、方法名)

        /// <summary>
        /// 获取方法调用者(DLL类、方法名)
        /// </summary>
        /// <returns></returns>
        public List<string> GetMehtodTrace()
        {
            List<string> lst = new List<string>();

            StackTrace trace = new StackTrace();
            foreach (StackFrame frame in trace.GetFrames())
            {
                var m = frame.GetMethod();
                if (m == null || m.ReflectedType == null || m.ReflectedType.Assembly == null)
                {
                    continue;
                }
                var tp = m.GetType();
                if (m.ReflectedType.Assembly.Location.ToUpper().Contains("SYSTEM.") == false && 
                    m.ReflectedType.Assembly.Location.ToUpper().Contains("MICROSOFT.NET") == false &&
                    m.ReflectedType.ToString().Contains("Loger") == false &&
                    m.ReflectedType.ToString().Contains("DataProvider") == false && 
                    m.ReflectedType.ToString().Contains("Microsoft.NET") == false)
                {
                    if (m.ReflectedType.ToString().Contains("CommonManage") &&
                        (m.Name == "SaveLog" ||m.Name == "SaveExceptionLog"
                        || m.Name == "GetMehtodTrace" || m.Name == "GetMehtodTraceStr"
                        ||m.Name== ".ctor"
                        ||m.Name=="GetDataSet"))
                    {
                        continue;
                    }

                    var rt = m.ReflectedType.Assembly.Location + " 类:" + m.ReflectedType.Name + " 方法:" + m.Name + "\r\n";

                    lst.Add(rt);

                    if(lst.Count>=2)
                    {
                        break;
                    }
                }
            }



            return lst;
        }

        /// <summary>
        /// 获取方法调用者(DLL类、方法名)
        /// </summary>
        /// <returns></returns>
        public string GetMehtodTraceStr()
        {
            string rt = "";
            var lst = GetMehtodTrace();
            rt = string.Concat(lst);
            return rt;
        }
        #endregion 获取方法调用者(DLL类、方法名)