標籤:style blog http io ar color os 使用 sp
多線程操作同一個檔案時會出現並發問題。解決的一個辦法就是給檔案加鎖(lock),但是這樣的話,一個線程操作檔案時,其它的都得等待,這樣的話效能非常差。另外一個解決方案,就是先將資料放在隊列中,然後開啟一個線程,負責從隊列中取出資料,再寫到檔案中。
下面我們講解一個實際項目中應用的案例,關於日誌的處理.這裡是使用ASP.NET MVC項目作為Demo。
方式一:使用隊列
思路:把所有產生的日誌資訊存放到一個隊列裡面,然後通過建立一個線程,不斷的從這個隊列裡面讀取異常資訊,然後往日誌裡面寫。也就是所謂的生產者、消費者模式。
1、建立一個類MyErrorAttribute,
using System.Web.Mvc; public class MyErrorAttribute : HandleErrorAttribute { public static Queue<Exception> ExceptionQueue = new Queue<Exception>(); public override void OnException(ExceptionContext filterContext) { ExceptionQueue.Enqueue(filterContext.Exception); filterContext.HttpContext.Response.Redirect("~/Error.html"); base.OnException(filterContext); }}
2、在FilterConfig類中進行如下修改:
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { //filters.Add(new HandleErrorAttribute()); filters.Add(new MyErrorAttribute()); } }3、在Gobal.asax.cs中的Application_Start事件裡添加如下代碼:
string filePath = Server.MapPath("~/Logs/"); ThreadPool.QueueUserWorkItem(o => { while(true) { if (MyErrorAttribute.ExceptionQueue.Count > 0) { Exception ex = MyErrorAttribute.ExceptionQueue.Dequeue(); if (ex != null) { string fileName = filePath + DateTime.Now.ToString("yyyy-MM-dd") + ".txt"; File.AppendAllText(fileName, ex.Message); } else { Thread.Sleep(50); } } else { Thread.Sleep(50); } } });
方式二:使用Redis與Log4Net完成分布式日誌記錄
Log4Net是用來記錄日誌的,可以將程式運行過程中的資訊輸出到一些地方(檔案、資料庫、EventLog等),日誌就是程式的黑匣子,可以通過
日誌查看系統的運行過程,從而發現系統的問題。日誌的作用:將運行過程的步驟、成功失敗記錄下來,將關鍵性的資料記錄下來分析系統問題所在。
對於網站來講,不能把異常資訊顯示給使用者,異常資訊只能記錄到日誌,出了問題把記錄檔發給開發人員,就能知道問題所在。
配置Log4Net環境
(1)建立一個WebApplication
(2)添加對log4net.dll的引用(bin\net\2.0\release 不能引用debug版本)(把相應的dll檔案拷貝到項目中的lib檔案夾下。)
(3)在Web.Config (或App.Config)添加配置
(4)初始化:在程式最開始加入log4net.Config.XmlConfigurator.Configure()
在要列印日誌的地方LogManager.GetLogger(typeof(Program)).Debug(“資訊”); 。通過LogManager.GetLogger傳遞要記錄的日誌類類名獲得這個類的ILog(這樣在記錄檔中就能看到這條日誌是哪個類輸出的了),然後調用Debug方法輸出訊息。因為一個類內部不止一個地方要列印日誌,所以一般把ILog聲明為一個static欄位。
Private static ILog logger=LogManager.GetLogger(typeof(Test))
輸出錯誤資訊用ILog.Error方法,第二個參數可以傳遞Exception對象。log.Error("***錯誤"+ex),log.Error("***錯誤",ex)
Appender:可以將日誌輸出到不同的地方,不同的輸出目標對應不同的Appender:RollingFileAppender(滾動檔案)、AdoNetAppender(資料庫)、SmtpAppender (郵件)等。
level(層級):標識這條日誌資訊的重要層級None>Fatal>ERROR>WARN>DEBUG>INFO>ALL,設定一個
Level,那麼低於這個Level的日誌是不會被寫到Appender中的.
Log4Net還可以設定多個Appender,可以實現同時將日誌記錄到檔案、資料、發送郵件等;可以設定不同的Appender的不同的Level,可以實現普通層級都記錄到檔案,Error以上層級發送郵件;可以實現對不同的類設定不同的Appender;還可以自訂Appender,這樣可以自己實現將Error資訊發簡訊等.
樣本:
1、配置Log4Net,在Web.config中添加如下配置:
<configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net> <!-- OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL --> <!-- Set root logger level to ERROR and its appenders --> <root> <level value="ALL"/> <appender-ref ref="SysAppender"/> </root> <!-- Print only messages of level DEBUG or above in the packages --> <logger name="WebLogger"> <level value="DEBUG"/> </logger> <appender name="SysAppender" type="log4net.Appender.RollingFileAppender,log4net" > <param name="File" value="App_Data/" /> <param name="AppendToFile" value="true" /> <param name="RollingStyle" value="Date" /> <param name="DatePattern" value=""Logs_"yyyyMMdd".txt"" /> <param name="StaticLogFileName" value="false" /> <layout type="log4net.Layout.PatternLayout,log4net"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" /> <param name="Header" value="----------------------header--------------------------" /> <param name="Footer" value="----------------------footer--------------------------" /> </layout> </appender> <appender name="consoleApp" type="log4net.Appender.ConsoleAppender,log4net"> <layout type="log4net.Layout.PatternLayout,log4net"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" /> </layout> </appender> </log4net>
2、添加ServiceStack.dll、ServiceStack.Interfaces.dll、ServiceStack.ServiceInterface.dll、log4net.dll的引用,然後建立一個類MyErrorAttribute,
using System.Web.Mvc;using ServiceStack.Redis; public static IRedisClientsManager clientsManager = new PooledRedisClientManager(new string[] { "127.0.0.1:6379"}); public static IRedisClient redisClient = clientsManager.GetClient(); public override void OnException(ExceptionContext filterContext) { redisClient.EnqueueItemOnList("errorMsg", filterContext.Exception.ToString()); filterContext.HttpContext.Response.Redirect("~/Error.html"); base.OnException(filterContext); }
3、在FilterConfig類中進行如下修改:
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { //filters.Add(new HandleErrorAttribute()); //filters.Add(new MyErrorAttribute()); filters.Add(new MyExceptionAttribute()); }}
4、在Gobal.asax.cs中的Application_Start事件裡添加如下代碼:
log4net.Config.XmlConfigurator.Configure(); //擷取Log4Net配置資訊 ThreadPool.QueueUserWorkItem(o => { while (true) { if (MyExceptionAttribute.redisClient.GetListCount("errorMsg") > 0) { string msg = MyExceptionAttribute.redisClient.DequeueItemFromList("errorMsg"); if (!string.IsNullOrEmpty(msg)) { ILog logger=LogManager.GetLogger("testError"); logger.Error(msg); //將異常資訊吸入Log4Net中 } else { Thread.Sleep(50); } } else { Thread.Sleep(50); } } });
檔案並發(Tlog)--隊列--Redis+Log4Net