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

注:这两个代码也是博主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. SpringBoot 块形式的配置文件写法(简单示例)

    1.配置文件写法 spring: profiles: dev quartz: auto-startup: true --- spring: profiles: local quartz: auto-s ...

  2. HCIP-ICT实战进阶07-BGP路由选路

    HCIP-ICT实战进阶07-BGP路由选路 1 BGP路径属性 任何一条BGP路由拥有多个路径属性; 当路由器将BGP路由拥有通告他的对等体时, 在Update报文中一并被通告的还有路由所携带的各个 ...

  3. 4、Normal Equation 的向量投影解法与几何和直觉解释

    参考:https://zhuanlan.zhihu.com/p/269232332 在线性回归的正交方程 ( Normal Equation )推导一文中提到使用 向量投影 的方法一步就能推导出 正交 ...

  4. Markdowm的下载方法

    1打开百度搜索,输入TYPORA打开下载页面,根据自己的系统(我的是WINDOWS64位)点"DOWN"进行下载安装. 2安装好后回到桌面新建一个文件夹(Markdown学习),然 ...

  5. 【转载】synopsys中工具介绍,VCS,DC,PT等

    https://blog.csdn.net/fangxiangeng/article/details/80981536

  6. WPF materialDesign 锁屏后界面卡死问题解决

    materialDesign的一个缓存机制问题,在xaml文件中Window属性添加一行: materialDesign:ShadowAssist.CacheMode="{x:Null}&q ...

  7. DevExpress.XtraEditors.ComboBoxEdit 只能选择不能在里面 输入数据

    DevExpress.XtraEditors.ComboBoxEdit 只能选择不能在里面 输入数据 combboxEdit.propoties.textEditStyle=DisableTextEd ...

  8. matlab判断操作

    类型判断 1.查看变量类型时可用class,判断某变量的类型值:会生成0或1,1-匹配,0-不匹配 isa(Data,'double') isa(Data,'cell') 2.也可用如下. strcm ...

  9. comment out one line in the file with sed

    sed -i "/test2/s/^/#/" test.log https://jaminzhang.github.io/linux/sed-command-usage-summa ...

  10. Cesium 结合Echarts绘制航线图

    <template> <div id="cesiumContainer"></div> </template> <script ...