Log4NET 日志分割删除与压缩解决思路(附源码)
最近公司发现,日志产生的太多了,于是让我写个方法来解决,一开始是让我删除,后来想了想让我先压缩再删除文件夹,下面提供两个版本的源代码及简单使用。
注:这两个代码也是博主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 日志分割删除与压缩解决思路(附源码)的更多相关文章
- log4net日志分割,按大小分割
最近写了一个socket通信的手表在线服务端,在日志方面,记录下Log4net日志分割 1.引入log4net.dll 2.web.config添加configsection handler 映射: ...
- arcgis api 3.x for js 解决 textSymbol 文本换行显示(附源码下载)
前言 关于本篇功能实现用到的 api 涉及类看不懂的,请参照 esri 官网的 arcgis api 3.x for js:esri 官网 api,里面详细的介绍 arcgis api 3.x 各个类 ...
- 日志组件Log2Net的介绍和使用(附源码开源地址)
Log2Net是一个用于收集日志到数据库或文件的组件,支持.NET和.NetCore平台. 此组件自动收集系统的运行日志(服务器运行情况.在线人数等).异常日志.程序员还可以添加自定义日志. 该组件支 ...
- (原创)通用查询实现方案(可用于DDD)[附源码] -- 设计思路
[声明] 写作不易,转载请注明出处(http://www.cnblogs.com/wiseant/p/3988592.html). [系列文章] 通用查询实现方案(可用于DDD)[附源码] -- ...
- arcgis api 3.x for js 入门开发系列批量叠加 zip 压缩 SHP 图层优化篇(附源码下载)
前言 关于本篇功能实现用到的 api 涉及类看不懂的,请参照 esri 官网的 arcgis api 3.x for js:esri 官网 api,里面详细的介绍 arcgis api 3.x 各个类 ...
- 通用查询实现方案(可用于DDD)[附源码] -- 设计思路
原文:通用查询实现方案(可用于DDD)[附源码] -- 设计思路 [声明] 写作不易,转载请注明出处(http://www.cnblogs.com/wiseant/p/3988592.html). ...
- leaflet结合geoserver利用WFS服务实现图层删除功能(附源码下载)
前言 leaflet 入门开发系列环境知识点了解: leaflet api文档介绍,详细介绍 leaflet 每个类的函数以及属性等等 leaflet 在线例子 leaflet 插件,leaflet ...
- cesium结合geoserver利用WFS服务实现图层删除(附源码下载)
前言 cesium 官网的api文档介绍地址cesium官网api,里面详细的介绍 cesium 各个类的介绍,还有就是在线例子:cesium 官网在线例子,这个也是学习 cesium 的好素材. 内 ...
- .Net高并发解决思路(附源码)
本文如有不对之处,欢迎各位拍砖扶正.另源码在文章最下面,大家下载过后先还原一下nuget包,需要改一下redis的配置,rabbitmq的配置以及Ef的连接字符串.另外使用的是CodeFirst,先u ...
- zookeeper 删除snapshot和transaction log的源码解读
转载请注明源地址http://www.cnblogs.com/dongxiao-yang/p/4910059.html zookeeper具有自动清除快照日志和事务日志的工能,可以在配置文件设置aut ...
随机推荐
- docker指令 —— MySQL一条龙服务
一.拉取MySQL镜像 简单粗暴拉取: docker pull mysql 拉取合适的版本,docker mysql Tag: # 例如拉取8.0.25 docker pull mysql:8.0.2 ...
- Linux配置文件和网络常用命令总结
Linux应用配置大全 Linux网络基本配置 最小化安装的话是没有ifconfig命令的需要使用yum search ifconfig查找,然后yum install net-tools.x86_6 ...
- nodejs. cron风,定时任务时间写法
export declare enum CronExpression { EVERY_SECOND = "* * * * * *", EVERY_5_SECONDS = " ...
- vue input输入框关键字筛选检索列表数据展示
想必大家在项目开发中难免会用到关键字筛选的功能,正好这次项目有需求要做这一块,就整理一下vue的input输入框输入关键字检索数据列表的代码.下面直接上代码: html: <!-- 筛选demo ...
- 微信小程序 switch
微信小程序 switch 组件 的大小调整方法: 加上 zoom:数值 ==>数值在0到1之间
- flutter 多种情况tabbar高度问题,普通使用和嵌套使用高度问题(Tab)。
众所周知tabbar的高度是不可改变的.比如我们普通的写一个tabbar. 先上效果图: 代码: Scaffold( appBar: AppBar( title: Text("TabBarD ...
- SpringMVC的学习day01
什么是SpringMVC 基于狂神说SpringMVC课程的学习 前面已经学习了spring.javaSE.javaweb.mybatis等知识,今天开始学习springMVC,是ssm框架的最后一个 ...
- vue3 自定义组件中使用 v-model
1.直接绑定 v-model,但是 Props 要固定为 modelValue 组件D: 注意这里的 Props 和 Emits,必须使用 Vue 提供的 defineProps() 和 define ...
- params的使用
今天在写vue的JavaScript的时候有个地方需要传很多参数,自己写不出来,求助 我的博博 后拿到神奇代码: 神奇代码中有params,俺自作聪明,以为他是一个json的数据,所以自己改了个名字 ...
- 【Hive 元数据和真实数据-TAB_COL_STATS记录错误问题】
MySql的元数据以及HDFS上数据的关系 元数据在DBS和TBLS上 (SD_ID) 1 首先通过hive创建一个表table_test 在hdfs的存储路径会生成相应的表 TBLS 也会更新内容进 ...