- 添加loghelp类
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
namespace XlsRecoder
{
public class LogHelper
{
private static object logLock = new object();
private static DateTime curDate = DateTime.MinValue;
public static void LogRetainDays(int days)
{
ThreadPool.QueueUserWorkItem(delegate
{
if (days >= 0)
{
DateTime now = DateTime.Now;
if (now.Subtract(curDate).TotalDays != 0.0)
{
curDate = now;
string text = "LOG";
string text2 = text + "\\" + DateTime.Now.ToString("yyyy-MM-dd");
DateTime dateTime = now.AddDays(-days);
if (Directory.Exists(text))
{
if (!Directory.Exists(text2))
{
Directory.CreateDirectory(text2);
}
lock (logLock)
{
try
{
string[] directories = Directory.GetDirectories(text, "????-??-??");
if (directories != null && directories.Length != 0)
{
for (int i = 0; i < directories.Length; i++)
{
DateTime value = Convert.ToDateTime(directories[i].Replace(text + "\\", ""));
if (dateTime.Subtract(value).TotalDays >= 0.0)
{
File.Delete(directories[i]);
}
}
}
return;
}
catch (Exception ex)
{
if (!File.Exists(text2 + "\\LogError.log"))
{
File.Create(text2 + "\\LogError.log").Dispose();
}
File.AppendAllLines(text2 + "\\LogError.log", new List<string> { DateTime.Now.ToString("MM-dd hh:mm:ss fff] ") + "error:" + ex.Message });
return;
}
}
}
Directory.CreateDirectory(text2);
}
}
});
}
public static void LogMessage(string fileName, string message)
{
ThreadPool.QueueUserWorkItem(delegate
{
string text = "LOG\\" + DateTime.Now.ToString("yyyy-MM-dd");
string path = text + "\\" + fileName;
lock (logLock)
{
try
{
if (!Directory.Exists(text))
{
Directory.CreateDirectory(text);
}
if (!File.Exists(path))
{
File.Create(path).Dispose();
}
File.AppendAllLines(path, new List<string> { DateTime.Now.ToString("MM-dd hh:mm:ss fff] ") + message });
}
catch (Exception ex)
{
if (!File.Exists(text + "\\LogError.log"))
{
File.Create(text + "\\LogError.log").Dispose();
}
File.AppendAllLines(text + "\\LogError.log", new List<string> { DateTime.Now.ToString("MM-dd hh:mm:ss fff] ") + "error:" + ex.Message });
}
}
});
}
}
}
- try... catch...方式进行捕捉异常,并打印到日志中
catch (Exception ex)
{
string str = ex.StackTrace;
LogHelper.LogMessage("LogRun.log", "异常" + str);
}