有些時候不方便F5調試。這樣輸出到文本。可以當調試,又可以當錯誤日誌,或操作日誌
上代碼
using System;
using System.Web;
using System.IO;
/// <summary>
/// 輸出文本日誌到文件~/log目錄
/// </summary>
/// <param name="title">方便查詢的關鍵字</param>
/// <param name="logStr">日誌內容</param>
public static void CreateWebLog(string title,string logStr)
{
try
{
string dir = System.Web.HttpContext.Current.Server.MapPath("~/log");
if (Directory.Exists(dir) == false)
{
Directory.CreateDirectory(dir);
}
string strFilePath = System.Web.HttpContext.Current.Server.MapPath("~/log/log_" + DateTime.Now.ToString("yyyyMMdd") + ".txt");
FileInfo logFile = new FileInfo(strFilePath);
System.IO.FileStream fs;
if (logFile.Exists)
{
fs = new System.IO.FileStream(strFilePath, System.IO.FileMode.Append);
}
else
{
fs = new System.IO.FileStream(strFilePath, System.IO.FileMode.Create);
}
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default);
sw.WriteLine("---------------------------------------------------------------------------------------");
sw.WriteLine("-----------------------------" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + "---------------------------------------");
sw.WriteLine("-----------------------------" + title + "----------------------------------------------------------");
sw.WriteLine("---------------------------------------------------------------------------------------");
sw.WriteLine(logStr);
sw.Close();
fs.Close();
}
catch (Exception)
{
}
}