Log4net 介紹
1、Log4net 是什麼?
Log4net 是 Apache 旗下一個開源的日誌框架的專案,它是Log4j 的一個複製版。Log4net中定義了多種日誌資訊輸出模式。它可以根據需要將日誌輸出到控制檯、文字檔案、windows 日誌事件檢視器中、括資料庫,郵件傳送,以便我們可以根據日誌快速定位線上系統的問題。
2、Log4net 日誌等級
從高到底分別為:OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL
二、ASP.NET MVC 使用 Log4net 示例2.1 如何安裝 Log4net Log4net
使用Nuget 安裝 Log4net(工具-NuGet包管理器-程式包管理器控制檯(N))使用管理NuGet程式包功能找到Log4net進行安裝。2.2 建立 log4net.config 配置檔案 ,並且將該檔案的屬性“複製到輸出目錄”修改為 “始終複製。
log4net.config內容如下:
2.3 新建LogHelper.cs通用日誌類
程式碼如下:
public class LogHelper { private ILog _log4Net = null; private const string DEFAULT_LOGGER_NAME = "Logger"; /// <summary> /// Prevents a default instance of the <see cref="LogWriter"/> class from being created. /// </summary> /// <param name="log4NetInstance">The log4net instance to be used.</param> private LogHelper(ILog log4NetInstance) { _log4Net = log4NetInstance; } /// <summary> /// Gets a logger with the specified configuration name. /// </summary> /// <param name="configName">Name of the logger in the configuration.</param> /// <returns>The logger obtained.</returns> /// <exception cref="System.Configuration.ConfigurationException">Thrown when no logger with the specified configuration name was found.</exception> public static LogHelper GetLogger(string configName) { var logger = LogManager.GetLogger(configName); if (logger == null) { throw new ArgumentException(string.Format("No logger configuration named '{0}' was found in the configuration.", configName), "configName"); } return new LogHelper(logger); } /// <summary> /// Gets the default. /// </summary> public static LogHelper Default { get { return GetLogger(DEFAULT_LOGGER_NAME); } } /// <summary> /// Writes an information level logging message. /// </summary> /// <param name="message">The message to be written.</param> public void WriteInfo(object message) { _log4Net.Info(message); } /// <summary> /// Writes a warning level logging message. /// </summary> /// <param name="message">The message to be written.</param> public void WriteWarning(object message) { _log4Net.Warn(message); } /// <summary> /// Writes a warning level logging message. /// </summary> /// <param name="message">The message to be written.</param> /// <param name="exception">The exception.</param> public void WriteWarning(object message, System.Exception exception) { _log4Net.Warn(message, exception); } /// <summary> /// Writes the error. /// </summary> /// <param name="message">The message to be written.</param> public void WriteError(object message) { _log4Net.Error(message); } /// <summary> /// Writes the error level logging message.. /// </summary> /// <param name="message">The message to be written.</param> /// <param name="exception">The exception.</param> public void WriteError(object message, System.Exception exception) { _log4Net.Error(message, exception); } /// <summary> /// Writes the fatal error level logging message.. /// </summary> /// <param name="message">The message to be written.</param> public void WriteFatal(object message) { _log4Net.Fatal(message); } /// <summary> /// Writes the fatal error level logging message.. /// </summary> /// <param name="message">The message to be written.</param> /// <param name="exception">The exception.</param> public void WriteFatal(object message, System.Exception exception) { _log4Net.Fatal(message, exception); } public void DeleteLog() { string logDirPath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "Log"); if (!Directory.Exists(logDirPath)) return; int days = 30; foreach (string filePath in Directory.GetFiles(logDirPath)) { DateTime dt; DateTime.TryParse(Path.GetFileNameWithoutExtension(filePath).Replace(@"Log\", "").Replace(".", "-"), out dt); if (dt.AddDays(days).CompareTo(DateTime.Now) < 0) { File.Delete(filePath); } } } }
2.4 AssemblyInfo.cs 檔案配置log4net.config
特別注意:針對為web專案要載入web專案對應的AssemblyInfo.cs檔案中去,這一點很關鍵要不然就不能輸出日誌檔案
[assembly: log4net.Config.XmlConfigurator(Watch = true, ConfigFileExtension = "config", ConfigFile = @"Configs\log4net.config")]
2.5 自定義日誌異常處理檔案:MyExceptionFileAttribute.cs
用來處理異常記錄日誌檔案,然後可以指定錯誤的跳轉頁面。
public override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); if (!string.IsNullOrWhiteSpace(filterContext.Exception.StackTrace)) { LogHelper.Default.WriteError(filterContext.Exception.StackTrace); } //頁面跳轉到錯誤頁面 filterContext.HttpContext.Response.Redirect("/Error"); }
2.6 Global.asax新增Log4Net的配置資訊
Application_Start.cs 方法加入下面兩行程式碼:
// 註冊log4net log4net.Config.XmlConfigurator.Configure(); // 註冊異常日誌檔案 GlobalFilters.Filters.Add(new MyExceptionFileAttribute());
測試用法
LoginController.cs 程式碼加一個異常
public ActionResult Index() { int a = 0; int b = 6 / a; return View(); }
效果展示:
個人部落格網站:https://programmerblog.xyz
最新評論