我正在嘗試向我的數據庫日誌目標添加一些定製。 在我NLog.config我有這樣的:NLog - 數據庫目標的運行時參數
<target name="DatabaseExample1" xsi:type="Database"
dbProvider="System.Data.SqlClient"
dbDatabase="${event-context:item=dbDatabase}"
dbUserName="${event-context:item=dbUserName}"
dbPassword="${event-context:item=dbPassword}"
dbHost="${event-context:item=dbHost}"
commandText="${event-context:item=commandText}">
</target>
在我的C#代碼,我有這樣的:
protected override void updateBeforeLog(LogEventInfo info)
{
info.Properties["dbDatabase"] = "TempDB";
info.Properties["dbUserName"] = "username";
info.Properties["dbPassword"] = "password";
info.Properties["dbHost"] = "SERVER\\SQLSERVER";
info.Properties["commandText"] = "exec InsertLog @LogDate, @LogLevel, @Location, @Message";
info.Parameters = new DatabaseParameterInfo[] {
new DatabaseParameterInfo("@LogDate", Layout.FromString("${date:format=yyyy\\-MM\\-dd HH\\:mm\\:ss.fff}")),
new DatabaseParameterInfo("@LogLevel", Layout.FromString("${level}")),
new DatabaseParameterInfo("@Location", Layout.FromString("${event-context:item=location}")),
new DatabaseParameterInfo("@Message", Layout.FromString("${event-context:item=shortmessage}"))
};
log.Log(info);
}
但我發現了,上面寫着一個SQL錯誤「必須聲明標量變量」 @LogDate 「」。
屬性正在工作,因爲連接成功。但由於某些原因,這些參數與命令中的標量變量不是「綁定」的。
如果我在NLog.config文件手動創建的參數,它完美的作品:
<target name="DatabaseExample1" xsi:type="Database"
dbProvider="System.Data.SqlClient"
dbDatabase="${event-context:item=dbDatabase}"
dbUserName="${event-context:item=dbUserName}"
dbPassword="${event-context:item=dbPassword}"
dbHost="${event-context:item=dbHost}"
commandText="${event-context:item=commandText}">
<parameter name="@LogDate" layout="${date:format=yyyy\-MM\-dd HH\:mm\:ss.fff}" />
<parameter name="@LogLevel" layout="${level}" />
<parameter name="@Location" layout="${event-context:item=location}" />
<parameter name="@Message" layout="${event-context:item=shortmessage}" />
</target>
但是,這違背了能夠自定義的CommandText和參數值在運行時的全部目的。
請幫我理解我需要做些什麼來使目標正確獲取參數的值。 謝謝!
更新
總的來說,我想有辦法通過C#代碼,自定義目標。我想依賴於NLog.config文件只需要很多。但看起來NLog與配置文件設置很相關,我試圖在該約束內工作,但要儘可能靈活。有了這個數據庫目標,如果我可以計算出如何以編程方式更新參數,那麼我可以在配置文件中擁有一個相當通用的目標,然後更新LogEventInfo屬性和參數以適應任何數據庫連接或存儲的需要程序來執行。
什麼SQL命令實際上看起來像'InsertLog'是它或你有實際的代碼..看起來像你缺少值關鍵字.. – MethodMan 2013-02-20 01:36:11
'InsertLog'是一個SQL Server數據庫中的存儲過程。所有實際的INSERT SQL都在那裏。正如我上面提到的,如果我把' '標籤放到NLog.config文件中,它就可以工作。 SQL部分正在工作。 –
jwatts1980
2013-02-20 14:42:39