using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Web.UI;
namespace OrderSystem
{
public class writeLog
{
/// <summary>
/// 寫入日志文件
/// </summary>
/// <param name="input"></param>
public static void WriteLogFile(string input)
{
///指定日志文件的目錄
string fname = "C:\\"+
DateTime.Now.Year + '-' +
DateTime.Now.Month + '-' +
DateTime.Now.Day + "_LogFile"+".txt";
if (!File.Exists(fname))
{
//不存在文件
File.Create(fname).Dispose();//創建該文件
}
/**/
///判斷文件是否存在以及是否大於2K
/* if (finfo.Length > 1024 * 1024 * 10)
{
/**/
//文件超過10MB則重命名
/* File.Move(fname, Directory.GetCurrentDirectory() + DateTime.Now.TimeOfDay + "\\LogFile.txt");
//刪除該文件
//finfo.Delete();
}*/
using (StreamWriter log = new StreamWriter(fname, true))
{
//FileStream fs = new FileStream(url, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);FileMode.Append
///設置寫數據流的起始位置為文件流的末尾
log.BaseStream.Seek(0, SeekOrigin.End);
///寫入“Log Entry : ”
log.Write("\n\rLog Entry : ");
///寫入當前系統時間並換行
log.Write("{0} {1} \n\r", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString());
///寫入日志內容並換行
log.Write(input + "\n\r");
//清空緩沖區
log.Flush();
//關閉流
log.Close();
}
}
/// <summary>
/// 將異常打印到LOG文件
/// </summary>
/// <param name="ex">異常</param>
/// <param name="LogAddress">日志文件地址</param>
public static void WriteLogTxt(Exception ex, string LogAddress = "")
{
//如果日志文件為空,則默認在Debug目錄下新建 YYYY-mm-dd_Log.log文件
if (LogAddress == "")
{
///指定日志文件的目錄
LogAddress = "E:\\" +
DateTime.Now.Year + '-' +
DateTime.Now.Month + '-' +
DateTime.Now.Day + "_Log.log";
}
FileInfo finfo = new FileInfo(LogAddress);
if (!finfo.Exists)
{
FileStream fs;
fs = File.Create(LogAddress);
fs.Close();
finfo = new FileInfo(LogAddress);
}
//把異常信息輸出到文件
StreamWriter sw = new StreamWriter(LogAddress, true);
sw.WriteLine("當前時間:" + DateTime.Now.ToString());
sw.WriteLine("異常信息:" + ex.Message);
sw.WriteLine("異常對象:" + ex.Source);
sw.WriteLine("調用堆棧:\n" + ex.StackTrace.Trim());
sw.WriteLine("觸發方法:" + ex.TargetSite);
sw.WriteLine();
sw.Close();
}
}
}