我的項目結構如下圖: 日誌幫助類庫需要log4net包:工具—NuGet包管理器—管理解決方案NuGet程式包 線程日誌幫助類 FlashLogger.cs 代碼 using System; using System.Collections.Concurrent; using System.Coll ...
我的項目結構如下圖:
日誌幫助類庫需要log4net包:工具—NuGet包管理器—管理解決方案NuGet程式包
線程日誌幫助類 FlashLogger.cs 代碼
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Web; using log4net; using log4net.Config; namespace FlashLog { public sealed class FlashLogger { /// <summary> /// 記錄消息Queue /// </summary> private readonly ConcurrentQueue<FlashLogMessage> _que; /// <summary> /// 信號 /// </summary> private readonly ManualResetEvent _mre; /// <summary> /// 日誌 /// </summary> private readonly ILog _log; /// <summary> /// 日誌 /// </summary> private static FlashLogger _flashLog = new FlashLogger(); private FlashLogger() { var configFile = new FileInfo(HttpContext.Current.Server.MapPath("~/log4net.config")); if (!configFile.Exists) { throw new Exception("未配置log4net配置文件!"); } // 設置日誌配置文件路徑 XmlConfigurator.Configure(configFile); _que = new ConcurrentQueue<FlashLogMessage>(); _mre = new ManualResetEvent(false); _log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); } /// <summary> /// 實現單例 /// </summary> /// <returns></returns> public static FlashLogger Instance() { return _flashLog; } /// <summary> /// 另一個線程記錄日誌,只在程式初始化時調用一次 /// </summary> public void Register() { Thread t = new Thread(new ThreadStart(WriteLog)); t.IsBackground = false; t.Start(); } /// <summary> /// 從隊列中寫日誌至磁碟 /// </summary> private void WriteLog() { while (true) { // 等待信號通知 _mre.WaitOne(); FlashLogMessage msg; // 判斷是否有內容需要如磁碟 從列隊中獲取內容,並刪除列隊中的內容 while (_que.Count > 0 && _que.TryDequeue(out msg)) { // 判斷日誌等級,然後寫日誌 switch (msg.Level) { case FlashLogLevel.Debug: _log.Debug(msg.Message, msg.Exception); break; case FlashLogLevel.Info: _log.Info(msg.Message, msg.Exception); break; case FlashLogLevel.Error: _log.Error(msg.Message, msg.Exception); break; case FlashLogLevel.Warn: _log.Warn(msg.Message, msg.Exception); break; case FlashLogLevel.Fatal: _log.Fatal(msg.Message, msg.Exception); break; } } // 重新設置信號 _mre.Reset(); Thread.Sleep(1); } } /// <summary> /// 寫日誌 /// </summary> /// <param name="message">日誌文本</param> /// <param name="level">等級</param> /// <param name="ex">Exception</param> public void EnqueueMessage(string message, FlashLogLevel level, Exception ex = null) { if ((level == FlashLogLevel.Debug && _log.IsDebugEnabled) || (level == FlashLogLevel.Error && _log.IsErrorEnabled) || (level == FlashLogLevel.Fatal && _log.IsFatalEnabled) || (level == FlashLogLevel.Info && _log.IsInfoEnabled) || (level == FlashLogLevel.Warn && _log.IsWarnEnabled)) { _que.Enqueue(new FlashLogMessage { Message = "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss,fff") + "]\r\n" + message, Level = level, Exception = ex }); // 通知線程往磁碟中寫日誌 _mre.Set(); } } public static void Debug(string msg, Exception ex = null) { Instance().EnqueueMessage(msg, FlashLogLevel.Debug, ex); } public static void Error(string msg, Exception ex = null) { Instance().EnqueueMessage(msg, FlashLogLevel.Error, ex); } public static void Fatal(string msg, Exception ex = null) { Instance().EnqueueMessage(msg, FlashLogLevel.Fatal, ex); } public static void Info(string msg, Exception ex = null) { Instance().EnqueueMessage(msg, FlashLogLevel.Info, ex); } public static void Warn(string msg, Exception ex = null) { Instance().EnqueueMessage(msg, FlashLogLevel.Warn, ex); } } /// <summary> /// 日誌等級 /// </summary> public enum FlashLogLevel { Debug, Info, Error, Warn, Fatal } /// <summary> /// 日誌內容 /// </summary> public class FlashLogMessage { public string Message { get; set; } public FlashLogLevel Level { get; set; } public Exception Exception { get; set; } } }View Code
WebForm項目創建:
1.需要引用線程日誌類庫 FlashLog
2.添加log4net配置文件 log4net.config,實現了資料庫及文件記錄日誌
CREATE TABLE ErrorLog ( dtDate DATETIME, sThread NVARCHAR(100), sLevel NVARCHAR(100), sLogger NVARCHAR(500), sMessage NVARCHAR(500), sException NTEXT )View Code
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/> </configSections> <log4net debug="false"> <!-- 將日誌信息寫入SQL Server資料庫--> <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender"> <bufferSize value="1" /> <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <connectionString value="SERVER=伺服器;DATABASE=資料庫;UID=用戶名;PWD=密碼;Connect Timeout=15;" /> <commandText value="INSERT INTO ErrorLog ([dtDate],[sThread],[sLevel],[sLogger],[sMessage],[sException]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" /> <parameter> <parameterName value="@log_date" /> <dbType value="DateTime" /> <layout type="log4net.Layout.RawTimeStampLayout" /> </parameter> <parameter> <parameterName value="@thread" /> <dbType value="String" /> <size value="100" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%t" /> </layout> </parameter> <parameter> <parameterName value="@log_level" /> <dbType value="String" /> <size value="200" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%p" /> </layout> </parameter> <parameter> <parameterName value="@logger" /> <dbType value="String" /> <size value="500" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%logger" /> </layout> </parameter> <parameter> <parameterName value="@message" /> <dbType value="String" /> <size value="3000" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%m" /> </layout> </parameter> <parameter> <parameterName value="@exception" /> <dbType value="String" /> <layout type="log4net.Layout.ExceptionLayout" /> </parameter> </appender> <!-- 將日誌信息寫入到項目日誌文件 --> <appender name="LogToFile" type="log4net.Appender.RollingFileAppender"> <encoding value="utf-8" /> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <file value="Logs\" /> <datePattern value="yyyy.MM.dd'.log'" /> <staticLogFileName value="false" /> <appendToFile value="true" /> <rollingStyle value="Composite" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="50MB" /> <layout type="log4net.Layout.PatternLayout"> <ConversionPattern value="%date 線程ID:[%thread] 日誌級別:%-5level 出錯類:%logger property:[%property{NDC}] - 錯誤描述:%message %newline" /> </layout> </appender> <!--設置根目錄,添加appenders並設置預設日誌等級 --> <root> <level value="All" /> <appender-ref ref="ADONetAppender" /> <appender-ref ref="LogToFile"/> </root> </log4net> </configuration>View Code
3.需要添加全局應用程式類 Global.asax
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.SessionState; namespace LogWeb { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { // 在應用程式啟動時運行的代碼 FlashLog.FlashLogger.Instance().Register(); } } }View Code
4.實例應用:訪問無效功能變數名稱時記錄錯誤日誌
try { string checkTonkenUrl = "http://url.abcde.com"; WebRequest wRequest = WebRequest.Create(checkTonkenUrl); wRequest.Method = "GET"; wRequest.ContentType = "text/html;charset=UTF-8"; WebResponse wResponse = wRequest.GetResponse(); Stream stream = wResponse.GetResponseStream(); StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8); string str = reader.ReadToEnd(); //url返回的值 } catch (Exception ex) { FlashLogger.Error("Error", ex); }View Code
到此,log4net日誌配置完成。
相關程式源碼可以點擊此處下載:鏈接: https://pan.baidu.com/s/1bu29Ba9zxyAs-oAmdaSI-A 密碼: upw2
另外附上自己整理的.net Core WebAPI 應用log4net,大家可以看下源碼:鏈接: https://pan.baidu.com/s/14wOIi1je0a02blM7_zlASg 密碼: gd9b