可定时执行的Web日志自动压缩清理程序
对于广大的Web开发人员,维护Web访问日志是一件经常性的工作,随着时间和访问量的提升,Web日志所占用的空间也会越来越大,如果将旧日志文件进行压缩会大大提升服务器硬盘空间的利用率,也方便日志文件的下载,手工操作总是比较繁琐的所以就写了下面的自动化程序,给大家分享一下
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Timers;
namespace WinCodeTest
{
/// <summary>
/// Web日志文件备份
/// </summary>
class FileZip
{
static List<string> listFile = new List<string>();
public static void ZipLog()
{
// Create a new Timer with Interval set to 10 seconds.
System.Timers.Timer aTimer = new System.Timers.Timer(1000);
aTimer.Elapsed += new ElapsedEventHandler(RunZip);
// Only raise the event the first time Interval elapses.
aTimer.AutoReset = true;
aTimer.Enabled = true;
Console.WriteLine("The Task Is Running... write 'q' exit");
while (Console.Read() != 'q') ;
}
/// <summary>
/// 遍历文件夹将所有文件进行压缩
/// </summary>
private static void RunZip(object source, ElapsedEventArgs e)
{
//存放日志文件的目录
string filePath = @"D:\WebLog\";
DateTime formatDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
DateTime startTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 02:10:00"));
//定时执行时间判断
double ts = (formatDate - startTime).TotalSeconds;
if (ts == 0)
{
GetAllFiles(filePath);
foreach (string file in listFile)
{
Console.WriteLine(DateTime.Now+"-=|备份:" + file);
ZipFile(file);
}
Console.WriteLine(DateTime.Now + "任务结束");
}
}
/// <summary>
/// 遍历目录下所有文件
/// </summary>
/// <param name="filePath"></param>
private static void GetAllFiles(string filePath)
{
//递归遍历所有子文件夹
string[] dir = Directory.GetDirectories(filePath);
for (int n = 0; n < dir.Length; n++)
{
GetAllFiles(dir[n]);
}
//保存文件夹内的文件路径 log文件
string[] file = Directory.GetFiles(filePath,"*.log");
for (int i = 0; i < file.Length; i++)
{
FileInfo fi = new FileInfo(file[i]);
//将两天前的日志加入压缩文件列表
if (fi.LastWriteTime < DateTime.Now.AddDays(-2))
{
listFile.Add(file[i]);
}
}
//删除25天前的备份文件 rar文件
string[] fileRar = Directory.GetFiles(filePath, "*.rar");
for (int i = 0; i < fileRar.Length; i++)
{
FileInfo fi = new FileInfo(fileRar[i]);
if (fi.LastWriteTime < DateTime.Now.AddDays(-25))
{
Console.WriteLine(DateTime.Now + "-=|删除:" + fileRar[i]);
fi.Delete();
}
}
}
/// <summary>
/// 根据文件路径压缩[删除源文件(-df);不包含文件路径(-ep)]
/// </summary>
/// <param name="str">文件路径</param>
/// <returns></returns>
private static string ZipFile(string strFileName)
{
string fullFileName = strFileName;
System.IO.FileInfo fi = new System.IO.FileInfo(fullFileName);
string FileName = @"C:\Program Files\WinRAR\Rar.exe"; //Winrar软件的安装目录,也可以将'rar.exe'放在程序的运行目录,不过需要更改一下路径
//执行压缩的命令,可以查看winrar软件的帮助文档,里面有详细的说明
string command = "-df -ep -tl -or a " + fi.Directory + @"\" + fi.Name.Replace(fi.Extension, "") + ".rar " + fullFileName;
System.Diagnostics.Process p = new System.Diagnostics.Process();
string ResultStr;
p.StartInfo.FileName = FileName;
p.StartInfo.Arguments = " " + command;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.ErrorDialog = false;
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
try
{
p.Start();
ResultStr = p.StandardError.ReadToEnd();
p.Close();
return ResultStr;
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Timers;
namespace WinCodeTest
{
/// <summary>
/// Web日志文件备份
/// </summary>
class FileZip
{
static List<string> listFile = new List<string>();
public static void ZipLog()
{
// Create a new Timer with Interval set to 10 seconds.
System.Timers.Timer aTimer = new System.Timers.Timer(1000);
aTimer.Elapsed += new ElapsedEventHandler(RunZip);
// Only raise the event the first time Interval elapses.
aTimer.AutoReset = true;
aTimer.Enabled = true;
Console.WriteLine("The Task Is Running... write 'q' exit");
while (Console.Read() != 'q') ;
}
/// <summary>
/// 遍历文件夹将所有文件进行压缩
/// </summary>
private static void RunZip(object source, ElapsedEventArgs e)
{
//存放日志文件的目录
string filePath = @"D:\WebLog\";
DateTime formatDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
DateTime startTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd 02:10:00"));
//定时执行时间判断
double ts = (formatDate - startTime).TotalSeconds;
if (ts == 0)
{
GetAllFiles(filePath);
foreach (string file in listFile)
{
Console.WriteLine(DateTime.Now+"-=|备份:" + file);
ZipFile(file);
}
Console.WriteLine(DateTime.Now + "任务结束");
}
}
/// <summary>
/// 遍历目录下所有文件
/// </summary>
/// <param name="filePath"></param>
private static void GetAllFiles(string filePath)
{
//递归遍历所有子文件夹
string[] dir = Directory.GetDirectories(filePath);
for (int n = 0; n < dir.Length; n++)
{
GetAllFiles(dir[n]);
}
//保存文件夹内的文件路径 log文件
string[] file = Directory.GetFiles(filePath,"*.log");
for (int i = 0; i < file.Length; i++)
{
FileInfo fi = new FileInfo(file[i]);
//将两天前的日志加入压缩文件列表
if (fi.LastWriteTime < DateTime.Now.AddDays(-2))
{
listFile.Add(file[i]);
}
}
//删除25天前的备份文件 rar文件
string[] fileRar = Directory.GetFiles(filePath, "*.rar");
for (int i = 0; i < fileRar.Length; i++)
{
FileInfo fi = new FileInfo(fileRar[i]);
if (fi.LastWriteTime < DateTime.Now.AddDays(-25))
{
Console.WriteLine(DateTime.Now + "-=|删除:" + fileRar[i]);
fi.Delete();
}
}
}
/// <summary>
/// 根据文件路径压缩[删除源文件(-df);不包含文件路径(-ep)]
/// </summary>
/// <param name="str">文件路径</param>
/// <returns></returns>
private static string ZipFile(string strFileName)
{
string fullFileName = strFileName;
System.IO.FileInfo fi = new System.IO.FileInfo(fullFileName);
string FileName = @"C:\Program Files\WinRAR\Rar.exe"; //Winrar软件的安装目录,也可以将'rar.exe'放在程序的运行目录,不过需要更改一下路径
//执行压缩的命令,可以查看winrar软件的帮助文档,里面有详细的说明
string command = "-df -ep -tl -or a " + fi.Directory + @"\" + fi.Name.Replace(fi.Extension, "") + ".rar " + fullFileName;
System.Diagnostics.Process p = new System.Diagnostics.Process();
string ResultStr;
p.StartInfo.FileName = FileName;
p.StartInfo.Arguments = " " + command;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.ErrorDialog = false;
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
try
{
p.Start();
ResultStr = p.StandardError.ReadToEnd();
p.Close();
return ResultStr;
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
}
}