我想通过NLog将消息记录到我的数据库。假设我准备好了数据库。
var dbTarget = new DatabaseTarget();
dbTarget.Name = "test";
dbTarget.ConnectionString = loggerModel.connection_string;
dbTarget.CommandText = "insert into NlogLogTable(LogDate,LogLevel,LogLogger,LogMessage,LogMachineName,LogUserName,LogCallSite,LogThreadId,LogThreadName,LogException,LogStackTrace) values(@LogDate,@LogLevel,@LogLogger,@LogMessage,@LogMachineName,@LogUserName,@LogCallSite,@LogThreadId,@LogThreadName,@LogException,@LogStackTrace);";
var dateTime = DateTime.Now.ToString();
var dateTimeOffset = DateTimeOffset.Now.ToString();
dbTarget.Parameters.Add(new DatabaseParameterInfo("@LogDate", new NLog.Layouts.SimpleLayout("${LogDate}")));
dbTarget.Parameters.Add(new DatabaseParameterInfo("@LogLevel", new NLog.Layouts.SimpleLayout("${LogLevel}")));
dbTarget.Parameters.Add(new DatabaseParameterInfo("@LogLogger", new NLog.Layouts.SimpleLayout("${LogLogger}")));
dbTarget.Parameters.Add(new DatabaseParameterInfo("@LogMessage", new NLog.Layouts.SimpleLayout("${LogMessage}")));
dbTarget.Parameters.Add(new DatabaseParameterInfo("@LogMachineName", new NLog.Layouts.SimpleLayout("${LogMachineName}")));
dbTarget.Parameters.Add(new DatabaseParameterInfo("@LogUserName", new NLog.Layouts.SimpleLayout("${LogUserName}")));
dbTarget.Parameters.Add(new DatabaseParameterInfo("@LogCallSite", new NLog.Layouts.SimpleLayout("${LogCallSite}")));
dbTarget.Parameters.Add(new DatabaseParameterInfo("@LogThreadId", new NLog.Layouts.SimpleLayout("${LogThreadId}")));
dbTarget.Parameters.Add(new DatabaseParameterInfo("@LogThreadName", new NLog.Layouts.SimpleLayout("${LogThreadName}")));
dbTarget.Parameters.Add(new DatabaseParameterInfo("@LogException", new NLog.Layouts.SimpleLayout("${LogException}")));
dbTarget.Parameters.Add(new DatabaseParameterInfo("@LogStackTrace", new NLog.Layouts.SimpleLayout("${LogStackTrace}")));
问题是我不知道如何将参数传递给它。假设LogDate
是今天的日期时间。我还有命令超时(毫秒)值,我也不知道如何传递它。
答案 0 :(得分:1)
有多种选项可以传递LogDate
和其他自定义值。
${event-properties:LogDate}
并将属性添加到logEvent。 (见EventProperties-Layout-Renderer。${date}
布局渲染器,例如${date:format=yyyyMMdd}
${mdc:item=String}
或${gdc:item=String}
对于命令超时,您可以使用2.或3.
the NLog wiki上列出了所有可能的值。
编辑:命令超时
的代码添加到目标:
dbTarget.Parameters.Add(new DatabaseParameterInfo("@LogDate", new NLog.Layouts.SimpleLayout("${event-properties:CommandTimeout}")));
编写事件时(使用流畅的界面,请参阅3)
var logger = LogManager.GetCurrentClassLogger();
logger.Info()
.Message("This is a test fluent message '{0}'.", DateTime.Now.Ticks)
.Property("CommandTimeout", YourCommandTimeout)
.Write();