最近公司发现,日志产生的太多了,于是让我写个方法来解决,一开始是让我删除,后来想了想让我先压缩再删除文件夹,下面提供两个版本的源代码及简单使用。
注:这两个代码也是博主CV的网上然后修改的,如侵权,请联系本人。(就算你联系了我也不会删,给你加个原文链接,啊嘻嘻嘻)
方法一:
在log4的config的配置文件中加上如下配置:
<logger name="ApplicationRollingFile"> <level value="ALL"/> <appender-ref ref="InfoLog"/> <appender-ref ref="WarnLog"/> <appender-ref ref="TraceLog"/> <appender-ref ref="ErrorLog"/> <appender-ref ref="FatalLog"/> </logger>
日志划分删除代码:
这里我加了个额外情况,就是生产环境中日志可能从别的地方烤过来,,,确实有这种情况。这个是自己设定多少天,然后传参传进函数,调用时会删除从今天开始算起,前面days的所有日志.但是删了万一日后要用,所以建议使用第二种方法,即先压缩,再删除原文件夹。
public class LogDivide { static ILog _log = null; static object lockHelper = new object(); public static void GetLog(int days) { if (null == _log) { lock (lockHelper) { if (null == _log) { StackTrace stackTrace = new StackTrace(0); 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(-1*days); 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); // 20220809 jyj 为了防止更换电脑日志从其他地方拷过来,这里采用修改时间 if (file.LastWriteTimeUtc < now) { try { file.Delete(); } catch (Exception) { } } } } } }); } } } //return _log; } }
方法二:
方法二呢
方法二呢就是上面说的先压缩,然后再删除原文件夹,这样做呢保守一点,推荐使用。
public class LogZip { /// <summary> /// 压缩文件 /// </summary> /// <param name="sourceFilePath"></param> /// <param name="destinationZipFilePath"></param> public static void CreateZip(string sourceFilePath, string destinationZipFilePath) { if (sourceFilePath[sourceFilePath.Length - 1] != Path.DirectorySeparatorChar) { sourceFilePath += Path.DirectorySeparatorChar; } ZipOutputStream zipStream = new ZipOutputStream(File.Create(destinationZipFilePath)); zipStream.SetLevel(6); // 压缩级别 0-9 CreateZipFiles(sourceFilePath, zipStream, sourceFilePath); zipStream.Finish(); zipStream.Close(); } /// <summary> /// 递归压缩文件 /// </summary> /// <param name="sourceFilePath">待压缩的文件或文件夹路径</param> /// <param name="zipStream">打包结果的zip文件路径(类似 D:\WorkSpace\a.zip),全路径包括文件名和.zip扩展名</param> /// <param name="staticFile"></param> private static void CreateZipFiles(string sourceFilePath, ZipOutputStream zipStream, string staticFile) { try { if (System.IO.File.Exists(sourceFilePath)) { Crc32 crc = new Crc32(); string[] filesArray = Directory.GetFileSystemEntries(sourceFilePath); foreach (string file in filesArray) { if (Directory.Exists(file)) //如果当前是文件夹,递归 { CreateZipFiles(file, zipStream, staticFile); } else //如果是文件,开始压缩 { FileStream fileStream = File.OpenRead(file); byte[] buffer = new byte[fileStream.Length]; fileStream.Read(buffer, 0, buffer.Length); string tempFile = file.Substring(staticFile.LastIndexOf("\\") + 1); ZipEntry entry = new ZipEntry(tempFile); entry.DateTime = DateTime.Now; entry.Size = fileStream.Length; fileStream.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; zipStream.PutNextEntry(entry); zipStream.Write(buffer, 0, buffer.Length); } } } } catch (Exception ex) { LogHelper.Error(ex.ToString()); } } public static void DeleteFolder(string path) { try { if (System.IO.File.Exists(path)) { // 去除文件夹和子文件的只读属性 System.IO.DirectoryInfo fileInfo = new DirectoryInfo(path); fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory; File.SetAttributes(path, FileAttributes.Normal); // 判断文件夹是否还存在 if (Directory.Exists(path)) { foreach (string f in Directory.GetFileSystemEntries(path)) { if (File.Exists(f)) { File.Delete(f); } else { DeleteFolder(f); } } } // 删除空文件夹 Directory.Delete(path); } } catch (Exception ex) { LogHelper.Error("日志压缩出现异常" + ex.ToString()); throw ex; } } }
标签:Log4NET,string,zipStream,sourceFilePath,源码,File,new,日志,文件夹 From: https://www.cnblogs.com/jyj666/p/16607262.html