web 介面 呼叫 記日誌
阿新 • • 發佈:2018-11-09
//獲取請求引數資訊 放在 public class ApiBaseController : Controller 裡 protected string PostParameter() { var byts = new byte[System.Web.HttpContext.Current.Request.InputStream.Length]; System.Web.HttpContext.Current.Request.InputStream.Read(byts, 0, byts.Length); return System.Text.Encoding.UTF8.GetString(byts); } namespace Sixcom.Common { public class LogHelp { private static string UsePath; static LogHelp() { UsePath = AppDomain.CurrentDomain.BaseDirectory + @"Logs\"; } /// <summary> /// 儲存日誌 /// </summary> /// <param name="msg">要記錄的資訊</param> /// <param name="subfolder">儲存路徑的子資料夾( 多級之間用 '\' 分隔 例如:Car\info)</param> public static void Log(LogType type, string msg,string subfolder = "") { StreamWriter sw = null; try { //判斷是否有子資料夾 if (!string.IsNullOrWhiteSpace(subfolder)) { subfolder = subfolder + @"\"; } string modules =
[email protected]"{UsePath}{subfolder}{type.ToString()}\"; if (!Directory.Exists(modules)) { Directory.CreateDirectory(modules); } //檔名稱 string fileName = string.Format($"{DateTime.Now.Date.ToString("yyyyMMdd")}.txt"); //日誌路徑+檔名 = 完全全路徑 string FullPath = Path.Combine(modules, fileName); sw = File.AppendText(FullPath); sw.WriteLine($"{DateTime.Now} {msg}" ); sw.WriteLine($"******************************"); } catch (Exception ex) { //日誌異常不捕獲,不影響程式 流程 //throw; } finally { if (sw != null) { sw.Flush(); sw.Close(); sw.Dispose(); } } } } /// <summary> /// 記錄型別 /// </summary> public enum LogType { /// <summary> /// 警告資訊 /// </summary> Debug = 0, /// <summary> /// 一般資訊 /// </summary> Info = 1, /// <summary> /// 警告資訊 /// </summary> Warn = 2, /// <summary> /// 異常資訊 /// </summary> Error = 3, /// <summary> /// 致命錯誤 /// </summary> Fatal = 4, } } //記錄呼叫資訊 LogHelp.Log(LogType.Info,[email protected]"【url】:{Request.RawUrl} 【引數】:{ PostParameter()}", @"ShopApi"); //列印後的效果如下: // 2018 / 5 / 3 16:59:18 【url】:/ ShopApiOrder / GetOreturnStatusByCode //【引數】:UnionId = 1 & CompanyId = 3 & ShopId = -1 & UserId = 66 & Code = XST1000218010500004 //* *****************************