2016年3月22日 星期二
[C#] NLog 建置筆記
/// <summary>
/// NLog 紀錄
/// </summary>
public static NLog.Logger NLogger = NLog.LogManager.GetCurrentClassLogger();
* 抓取Session的值
參考 https://github.com/NLog/NLog/wiki/AspNetSession-layout-renderer
程式:
Session["user"] = new UserInfo { Name= "johnDoe", Id = 100};
nlog config設定 :
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="logfile" xsi:type="File" fileName="file.txt" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logfile" layout="${aspnet-session:Variable=User.Name:EvaluateAsNestedProperties=true}/>
</rules>
</nlog>
發生【LayoutRenderer cannot be found: 'aspnet-request'】的錯誤時,
需安裝 NLog.Extended.dll 可擴增功能
http://kevintsengtw.blogspot.tw/2011/10/nlog-advanced-net-logging-3.html
Session格式範例
http://nlog-project.org/documentation/v2.0.1/html/T_NLog_LayoutRenderers_AspNetSessionValueLayoutRenderer.htm
You can set the value of an ASP.NET Session variable by using the following code:
C#
HttpContext.Current.Session["myvariable"] = 123;
HttpContext.Current.Session["stringvariable"] = "aaa BBB";
HttpContext.Current.Session["anothervariable"] = DateTime.Now;
Example usage of ${aspnet-session}:
${aspnet-session:variable=myvariable} - produces "123"
${aspnet-session:variable=anothervariable} - produces "01/01/2006 00:00:00"
${aspnet-session:variable=anothervariable:culture=pl-PL} - produces "2006-01-01 00:00:00"
${aspnet-session:variable=myvariable:padding=5} - produces " 123"
${aspnet-session:variable=myvariable:padding=-5} - produces "123 "
${aspnet-session:variable=stringvariable:upperCase=true} - produces "AAA BBB"
常用的:
${time} 時間
${asp-session:variable=String} Session
${aspnet-request:cookie=String:serverVariable=String:queryString=Strin:item=String:form=String}
Cookie_ queryString
${basedir} 根目錄
${date} 日期+時間
${level} log等級
${newline} 換行
${shortdate} yyyy-MM-dd 日期
請參考 https://github.com/nlog/NLog/wiki/Layout%20Renderers
-------------------------------------
NLog config設定的變數宣告方式:
${APName}_${mdc:item=DateName}
程式碼:
//以時間來命名 NLog 檔名,需在NLog.config 宣告 ${mdc:item=DateName} 變數來使用
NLog.MappedDiagnosticsContext.Set("DateName", DateTime.Now.ToString("HH-mm-ss"));
訂閱:
張貼留言 (Atom)
0 意見:
張貼留言