public class LogHelper
{
#region 错误日志记录
public static string webIniErrorLogName = HttpRuntime.AppDomainAppPath + "WebLog\E_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";//Web错误日志名称
/// <summary>
/// 创建日志目录
/// </summary>
private static void CreateDirectory()
{
if (!Directory.Exists(HttpRuntime.AppDomainAppPath + "WebLog"))
{
Directory.CreateDirectory(HttpRuntime.AppDomainAppPath + "WebLog");
}
}
/// <summary>
/// 创建错误日志文件
/// </summary>
private static void CreateMarsWebErrorLogFile()
{
CreateDirectory();
if (!File.Exists(webIniErrorLogName))
{
string filename = webIniErrorLogName;//文件名称
using (FileStream myFs = new FileStream(filename, FileMode.Create))
{
StreamWriter mySw = new StreamWriter(myFs);
mySw.Write("");
mySw.Dispose();
myFs.Close();
myFs.Dispose();
}
}
}
/// <summary>
/// 写错误日志调用
/// </summary>
/// <param name="errorMsg"></param>
public static void WriteMessageErrorLog(string errorMsg)
{
System.Threading.ParameterizedThreadStart logdele = new ParameterizedThreadStart(WriteMessageELog);
AsyncCallback asyncCallback = new AsyncCallback(Async_ApplyStyleAndData);
logdele.BeginInvoke(errorMsg, asyncCallback, null);
}
/// <summary>
/// 写错误日志方法
/// </summary>
/// <param name="errorMsg"></param>
private static void WriteMessageELog(object errorMsg)
{
CreateMarsWebErrorLogFile();
int i = 0;
do
{
try
{
string logFilePath = webIniErrorLogName;
FileStream fs = new FileStream(logFilePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
string context = "
" + DateTime.Now + " " + errorMsg;
byte[] contextByte = Encoding.UTF8.GetBytes(context);
fs.Write(contextByte, 0, contextByte.Length);
fs.Flush();
fs.Close();
fs.Dispose();
break;
}
catch (Exception)
{
Thread.Sleep(500);
}
} while (i < 3);
}
/// <summary>
/// 回调
/// </summary>
/// <param name="ar"></param>
public static void Async_ApplyStyleAndData(IAsyncResult ar) { }
/// <summary>
/// 监测时间
/// </summary>
private void CheckTime()
{
if (DateTime.Now.Hour.ToString("00") == "00")
{
webIniErrorLogName = HttpRuntime.AppDomainAppPath + "WebLog\E_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";//Web错误日志名称
}
}
/// <summary>
/// 开始检测
/// </summary>
public void DoCheckTime()
{
while (true)
{
CheckTime();
Thread.Sleep(180000);//半小时执行一次
}
}
#endregion
}