2016年5月20日 星期五

JSNlog 結合NLog與Elmah

原本只有在使用Elmah及NLog,前幾天看到有一個東西叫JSNLog,而且可以整合在一起,終於有個方便的東西可以記錄JS到底發生了甚麼事,直接來看怎麼使用吧。
  1. 使用Nuget安裝以下幾個套件
    • Elmah相關:Elmah、Elmah Code Library、Elmah MVC、Elmah On Xml Log
    • NLog相關:NLog、NLog.config、NLog.schema、NLog.elmah
    • JSNLog相關: JSNLog、JSNLog.NLog
  2. 安裝完就來做設定,基本上就兩個地方,第一個是NLog.config要設定寫到Elmah的格式,第二個就是在頁面上要放jsnlog.js檔案
    • NLog.config的部分
    • <targets> 
          <target xsi:type="Elmah"
                  name="elmahWithLogLevelAsType"
                  layout="
                  Log等級:${level:uppercase=true}
                  Source:${callsite:className=true}
                  錯誤訊息:${message}
                  StackTrace:${exception:format=stacktrace}
                  Exception類別:${exception:format=type}
                  Exception訊息:${exception:format=message}
                  EXCEPTION OCCURRED:         ${exception:format=type,message,method:maxInnerExceptionLevel=5:innerFormat=shortType,message,method}"
                  LogLevelAsType="true" />
      <targets />
      <rules>
          <logger name="*" minlevel="Trace" writeTo="elmahWithLogLevelAsType" />
      <rules />
      
    • 因為我是用MVC專案來做,所以只要把引用的段落放在_Layout裡
    • //這段加在_Layout.cshtml的最所有JS檔的最後面
      @Html.Raw(JSNLog.JavascriptLogging.Configure())
      
  3. 再來就可以測試是否成功,在瀏覽器上用console輸入JL().info("test info"),看是否可正常送回後台,再來就是查看Elmah是否成功紀錄此訊息。
     
參考來源:JSNLog with ASP MVC Web

沒有留言 :

張貼留言