在MVC專案下建立Log類別
public class LogWriter
{
/// <summary>路徑</summary>
private static string Path = "C:\\LogFile";
/// <summary>檔案名稱</summary>
private static string Name = "Log";
/// <summary>
/// 設定路徑和名稱
/// </summary>
/// <param name="NewPath">路徑</param>
/// <param name="NewName">名稱</param>
public static void SetPathAndName(string NewPath, string NewName)
{
Path = NewPath;
Name = NewName;
}
/// <summary>
/// 產生Log檔
/// </summary>
public static void CreateLogger()
{
//如果此路徑沒有資料夾
if (!Directory.Exists(Path))
{
//新增資料夾
Directory.CreateDirectory(Path);
}
WriteLog("=======================================");
WriteLog("程式啟動 : " + DateTime.Now.ToString());
WriteLog("=======================================");
}
/// <summary>
/// 寫入Log
/// </summary>
/// <param name="log">Log內容</param>
public static void WriteLog(string log)
{
if (!Directory.Exists(Path))
CreateLogger();
using (StreamWriter sw = File.AppendText(Path + "\\" + Name))
sw.WriteLine(log);
}
/// <summary>
/// 寫入Log
/// </summary>
/// <param name="LogType">Log類別</param>
/// <param name="ClassName">使用GetType的Name或FullName</param>
/// <param name="MethodName">使用MethodBase.GetCurrentMethod</param>
/// <param name="Message">Log內容</param>
/// <returns></returns>
public static void WriteLog(ELogType LogType, string ClassName, string MethodName, string Message)
{
if (!Directory.Exists(Path))
CreateLogger();
using (StreamWriter sw = File.AppendText(Path + "\\" + Name)){
sw.WriteLine($"[{LogType}] {Regex.Replace(ClassName, "Controller", string.Empty)}[{MethodName}] {Message}");
}
}
}
建立Log用Enum
public class ConstEnum
{
/// <summary>Log列舉</summary>
public enum ELogType
{
/// <summary>資訊</summary>
INFO,
/// <summary>警告</summary>
WARN,
/// <summary>錯誤</summary>
ERROR
}
}
在應用程式開始和結束的地方加入
namespace WebProjectName
{
/// <summary>執行端</summary>
public class MvcApplication : System.Web.HttpApplication
{
/// <summary>應用程式開始</summary>
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
//加入路由
RouteConfig.RegisterRoutes(RouteTable.Routes);
//封裝JS和CSS檔
BundleConfig.RegisterBundles(BundleTable.Bundles);
//啟動Log記錄
LogWriter.SetPathAndName("C:\\LogFile", "Log");
LogWriter.CreateLogger();
}
/// <summary>應用程式結束</summary>
protected void Application_End()
{
LogWriter.WriteLog("=======================================");
LogWriter.WriteLog("程式結束Application_End : " + DateTime.Now.ToString());
LogWriter.WriteLog("=======================================");
}
/// <summary>程式出錯</summary>
protected void Application_Error()
{
Exception ErrorMsg = Server.GetLastError();
LogWriter.WriteLog($"[Application_Error] Exception:{ErrorMsg.GetType().Name}({ErrorMsg.Message}) \nSource:{ErrorMsg.Source} \nStackTrace:{ErrorMsg.StackTrace}");
}
}
}
使用方式
LogWriter.WriteLog(ELogType.INFO, GetType().Name, MethodBase.GetCurrentMethod().Name, "訊息");