任何程序我想無論是在調試開發階段還是上線運營階段,都能夠使人“放心”,不要出什么意外,也不要玩什么心跳;那就需要比較到位和及時的異常與錯誤日志模塊。
本文將簡要描述ELMAH、MVC4與SQLite這個中小程序的好伙伴般的精干小團隊。
1. ELMAH 可以通過NuGet來獲取,建議選擇ELMAH.MVC這個版本主要針對MVC架構,基本不需要什么配置; 當然也可以選擇原始的ELMAH版本,只不過是多了些配置而已。
1 2 <elmah> 3 <!-- <errorMail from="roger_zhang@newsoft.com.cn" 4 to="mqgh@sina.com" 5 subject="Roger is testing ELMAH log Modeul" 6 async="true" 7 smtpPort="25" 8 smtpServer="smtpcom.263xmail.com" 9 userName="XXX" 10 password="*****" />--> 11 <!--<errorLog type="Elmah.MemoryErrorLog, Elmah" size="100" />--> 12 <!--<errorLog type="Elmah.XmlFileErrorLog, Elmah" logPath="~/App_Data/ElmahXML_Logs" />--> 13 <errorLog type="Elmah.SQLiteErrorLog, Elmah" connectionStringName="ElmahDB" /> 14 </elmah>
可以通過以上配置來分別測試三種不同的日志記錄模式:MemoryErrorLog、XmlFileErrorLog、SQLiteErrorLog、Email。
2. Controller端簡單的寫兩個異常測試一下,看看效果,混個臉熟先。
1 public ActionResult Index() 2 { 3 ViewBag.Message = "修改此模板以快速啟動你的 ASP.NET MVC 應用程序。"; 4 return View(); 5 } 6 public PartialViewResult About() 7 { 8 ViewBag.Message = "Your app description page."; 9 var a = _db.CardRecordItem.SingleOrDefault(x => x.CardId == 999999999).CardId;//此處會服空引用異常,因為本表中不存在這個ID 10 return PartialView(); 11 } 12 public ActionResult Contact() 13 { 14 ViewBag.Message = "Your contact page."; 15 int num = Convert.ToInt32("XXX");//此處會報類型轉換異常 16 return View(); 17 }
3.SQLite的配合。same step 用NuGet來獲取最新版的SQLite,並在web.config文件中做相應的配置。
<add name="ElmahDB" connectionString="data source=~/App_Data/Elmah.db" />
4.測試結果出來啦,只需要點About和Contact兩個頁面即可。
5.補充sqlite的簡單操作,來確認此Error數據是否存入相應數據庫。
下載Sqlite.exe假如放在D:\Programefiles\處; 相應的Elmah.db放在App_Data下。
D:\Program Files>sqlite3.exe H:\GitHub\RogerHelloWorld\MvcApplication14\App_Dat\Elmah.db;
SQLite version 3.7.15.2 2013-01-09 11:53:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
接下來就可以Selet嘍。