1.Write方法是写日志主要方法。
2.DeleteLog方法是删除指定日期之前生成的日志。
public static void Write(string Msg)
{
string strPath;
DateTime dt = DateTime.Now;
try
{
strPath =AppDomain.CurrentDomain.BaseDirectory + “\Log”;
if (Directory.Exists(strPath) == false)
{
Directory.CreateDirectory(strPath);
}
DeleteLog(strPath);
strPath = strPath + "\\" + dt.ToString("yyyyMMdd") + ".txt";<br /> StreamWriter FileWriter = new StreamWriter(strPath, true);<br /> FileWriter.WriteLine(dt.ToString("HH:mm:ss") + Msg);<br /> FileWriter.Close();<br /> }<br /> catch (Exception ex)<br /> {<br /> string str = ex.Message.ToString();<br /> }<br /> }<br /> public static void DeleteLog(string sLogPath)<br /> {<br /> //string strFolderPath = @"E:\Zhao\我的代码\f福建中医药大学附属人民医院\定制化服务\bin\Debug\logs";
DirectoryInfo dyInfo = new DirectoryInfo(sLogPath);<br /> //获取文件夹下所有的文件<br /> foreach (FileInfo feInfo in dyInfo.GetFiles())<br /> {<br /> //判断文件日期是否小于指定日期,是则删除<br /> if (feInfo.CreationTime < DateTime.Now.AddDays(-15))<br /> feInfo.Delete();<br /> }<br /> }
原文链接:https://blog.csdn.net/weixin_42800530/article/details/83546201
public static void WriteLog(Exception ex)
{
string errorTime = “异常时间:” + DateTime.Now.ToString();
string errorAddress = “异常地址:” + HttpContext.Current.Request.Url.ToString();
string errorInfo = “异常信息:” + ex.Message;
string errorSource = “错误源:” + ex.Source;
string errorType = “运行类型:” + ex.GetType();
string errorFunction = “异常函数:” + ex.TargetSite;
string errorTrace = “堆栈信息:” + ex.StackTrace;
HttpContext.Current.Server.ClearError();
System.IO.StreamWriter writer = null;
try
{
//写入日志
string path = string.Empty;
path = HttpContext.Current.Server.MapPath(“~/ErrorLogs/“);
//不存在则创建错误日志文件夹
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path += string.Format(@”{0}.txt”, DateTime.Now.ToString(“yyyy-MM-dd”));
writer = !System.IO.File.Exists(path) ? System.IO.File.CreateText(path) : System.IO.File.AppendText(path); //判断文件是否存在,如果不存在则创建,存在则添加
writer.WriteLine(“用户IP:” + HttpContext.Current.Request.UserHostAddress);
writer.WriteLine(errorTime);
writer.WriteLine(errorAddress);
writer.WriteLine(errorInfo);
writer.WriteLine(errorSource);
writer.WriteLine(errorType);
writer.WriteLine(errorFunction);
writer.WriteLine(errorTrace);
writer.WriteLine(“**“);
}
finally
{
if (writer != null)
{
writer.Close();
}
}
}