I want to log message to my database by NLog. Suppose I have the database ready.
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}")));
The thing is that I don't know how to pass the parameters to it. Let's say LogDate
is today's datetime. Also I have command timeout (milliseconds) value, I am not sure how to pass it as well.
There are various options to pass
LogDate
and other custom values.${event-properties:LogDate}
and add the properties to your logEvent. (see EventProperties-Layout-Renderer.${date}
layout renderer, like${date:format=yyyyMMdd}
${mdc:item=String}
or${gdc:item=String}
For the command timeout you can use 2. or 3.
All possible values are listed on the NLog wiki.
edit: the code for command timeout
Add to the target:
When writing the event (using the fluent interface, see 3)