log4net自动删除日志文件

晚上关于删除的日志文件主要有 https://blog.csdn.net/hellolib/article/details/78316253, 其实我这里的实现方式和他差不多,不过我这里不用配置时间, 直接写死 删除10天以前的日志数据,

  static ILog _log = null;
        static object lockHelper = new object();
        private ILog GetLog()
        {
 
            if (null == _log)
            {
                lock (lockHelper)
                {
                    if (null == _log)
                    {
                        StackTrace stackTrace = new StackTrace(this._skipFrames);
                        StackFrame stackFrame = stackTrace.GetFrame(0);
                        MethodBase methodBase = stackFrame.GetMethod();
 
                        // ApplicationRollingFile在.config文件中配置的名称
                        _log = LogManager.GetLogger("ApplicationRollingFile");
                        Task.Run(()=> {
                            var apps = _log.Logger.Repository.GetAppenders();
                            if (apps.Length <= 0)
                            {
                                return;
                            }
                            var now = DateTime.UtcNow.AddDays(-10);
                            foreach (var item in apps)
                            {
                                if (item is RollingFileAppender)
                                {
                                    RollingFileAppender roll = item as RollingFileAppender;
                                    var dir = Path.GetDirectoryName(roll.File);
                                    var files = Directory.GetFiles(dir, "*.txt");
                                    //var sample = "log.txt2017-10-23.txt";
 
                                    foreach (var filePath in files)
                                    {
                                        var file = new FileInfo(filePath);
                                        if (file.CreationTimeUtc < now) {
                                            try
                                            {
                                                file.Delete();
                                            }
                                            catch (Exception)
                                            {
 
                                            }
                                        }
                                    }
                                }
                            }
                        });
                    }
                }
            }
                        
            return _log;
        }

posted on 2019-07-09 13:55  dz45693  阅读(3590)  评论(0编辑  收藏  举报

导航