最近公司发现,日志产生的太多了,于是让我写个方法来解决,一开始是让我删除,后来想了想让我先压缩再删除文件夹,下面提供两个版本的源代码及简单使用。

注:这两个代码也是博主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 日志分割删除与压缩解决思路(附源码)的更多相关文章

  1. log4net日志分割,按大小分割

    最近写了一个socket通信的手表在线服务端,在日志方面,记录下Log4net日志分割 1.引入log4net.dll 2.web.config添加configsection handler 映射: ...

  2. arcgis api 3.x for js 解决 textSymbol 文本换行显示(附源码下载)

    前言 关于本篇功能实现用到的 api 涉及类看不懂的,请参照 esri 官网的 arcgis api 3.x for js:esri 官网 api,里面详细的介绍 arcgis api 3.x 各个类 ...

  3. 日志组件Log2Net的介绍和使用(附源码开源地址)

    Log2Net是一个用于收集日志到数据库或文件的组件,支持.NET和.NetCore平台. 此组件自动收集系统的运行日志(服务器运行情况.在线人数等).异常日志.程序员还可以添加自定义日志. 该组件支 ...

  4. (原创)通用查询实现方案(可用于DDD)[附源码] -- 设计思路

    [声明] 写作不易,转载请注明出处(http://www.cnblogs.com/wiseant/p/3988592.html).   [系列文章] 通用查询实现方案(可用于DDD)[附源码] -- ...

  5. arcgis api 3.x for js 入门开发系列批量叠加 zip 压缩 SHP 图层优化篇(附源码下载)

    前言 关于本篇功能实现用到的 api 涉及类看不懂的,请参照 esri 官网的 arcgis api 3.x for js:esri 官网 api,里面详细的介绍 arcgis api 3.x 各个类 ...

  6. 通用查询实现方案(可用于DDD)[附源码] -- 设计思路

    原文:通用查询实现方案(可用于DDD)[附源码] -- 设计思路 [声明] 写作不易,转载请注明出处(http://www.cnblogs.com/wiseant/p/3988592.html).   ...

  7. leaflet结合geoserver利用WFS服务实现图层删除功能(附源码下载)

    前言 leaflet 入门开发系列环境知识点了解: leaflet api文档介绍,详细介绍 leaflet 每个类的函数以及属性等等 leaflet 在线例子 leaflet 插件,leaflet ...

  8. cesium结合geoserver利用WFS服务实现图层删除(附源码下载)

    前言 cesium 官网的api文档介绍地址cesium官网api,里面详细的介绍 cesium 各个类的介绍,还有就是在线例子:cesium 官网在线例子,这个也是学习 cesium 的好素材. 内 ...

  9. .Net高并发解决思路(附源码)

    本文如有不对之处,欢迎各位拍砖扶正.另源码在文章最下面,大家下载过后先还原一下nuget包,需要改一下redis的配置,rabbitmq的配置以及Ef的连接字符串.另外使用的是CodeFirst,先u ...

  10. zookeeper 删除snapshot和transaction log的源码解读

    转载请注明源地址http://www.cnblogs.com/dongxiao-yang/p/4910059.html zookeeper具有自动清除快照日志和事务日志的工能,可以在配置文件设置aut ...

随机推荐

  1. [OC] UIWebView APIs 的替换 以及转用WKWebView后的部分问题

    一.检查工程中的 UIWebView 1.打开终端,cd + 把项目的工程文件所在文件夹拖入终端(即 得到项目的工程文件所在的路径) 2.输入以下命令: grep -r UIWebView . 注意最 ...

  2. 用“餐厅打包”的故事说明白Python里面的自定义函数

    注:博主并非Python专业程序员,年龄12岁,Python龄不到1岁,才疏学浅,如有错误还请大佬指教! 希望能通过本专栏帮助到一些Python小白! 嗨~大家好!上篇博文咱们说了,万一有一些上万行才 ...

  3. CSS的拾遗(1)

    CSS的拾遗(1) 1.padding: (1)定义:在一个声明中设置所有内边距属性 (2)用法: 例子 1:上,右,下,左 padding:10px 5px 15px 20px; 上内边距是 10p ...

  4. maven jar包新版本检测工具推荐

    为什么需要 经常使用maven来构建项目的朋友,应该遇到过类似这样的情况:项目通过maven引入了很多jar包,随着时间推移,这些jar包都有了更优的新版本出来,想升级,但又觉得很繁琐.主要是因为两方 ...

  5. firefox 安装旧版flash播放器

    国内恶心的特供版flash用是不可能在用了,用旧版的火狐和旧版的flash播放器,亲测可用. 下载旧版本的火狐浏览器67.04 https://ftp.mozilla.org/pub/firefox/ ...

  6. Java基础__03.异常

    什么是异常? 异常是指程序运行中出现的各种例外情况,如文件找不到.网络连接失败.传参错误...异常发生在程序运行期间,它影响了正常的程序执行流程. 异常体系结构: 在java中,异常是被当作对象来处理 ...

  7. Android 6.0动态添加权限(Finn_ZengYuan博客)

    1,随着手机版本变高,各种权限也有所限制:以下代码可人性化添加动态权限: 权限工具类1,2,3,4: 1,FinnPermissionConfig.CLass package com.finn.too ...

  8. Spring MVC文件上传下载

    Spring MVC文件上传下载 单文件上传 底层是使用Apache fileupload 组件完成上传,Spring MVC对这种方式进行封装. pom.xml <dependency> ...

  9. startActivity 新开一个Activity

    private void startActivity(Intent intent) { Context ctx = ApplicationController.getTopActivity(); if ...

  10. 所谓的安装phpmyadmin

    所谓的安装phpmyadmin, 或者 安装drush, 都是下载一个文件, 然后URL访问或者命令行访问这个文件, 进入到某个页面或者获得某个结果.刚开始觉得很神秘哦, 为什么?--安装软件分两种1 ...