Ms precision datetime logging using the NLog event context context mapper

I am trying to write some audit data to a SQL Server 2008 table using NLog 2. To be able to pass parameters to a SQL query, I use LogEventInfo and the Event Context Context Mapper .

The log itself works, but the datetime is saved only with a second precision. I want to be able to store with millisecond precision, but have not found anything that will show me how to do this.

This is the C # code where I register the event:

private void LogMessage(DateTime requestDateTime) { LogEventInfo theEvent = new LogEventInfo(LogLevel.Debug, "", "Pass my custom value"); theEvent.Properties["RequestDate"] = requestDateTime; } 

This is the goal that I have in my NLog.config configuration:

 <target xsi:type="Database" name="SqlLog" dbProvider="sqlserver" connectionString="server=localhost;database=Test;integrated security=sspi"> <commandText> INSERT [dbo].[ApiLog] ( [ServerName], [RequestDate] ) VALUES (@ServerName, @RequestDate); </commandText> <parameter name="@ServerName" layout="${machinename}"/> <parameter name="@RequestDate" layout="${event-context:item=RequestDate}"/> </target> 

There is a workaround that I found using theEvent.Properties["RequestDate"] = requestDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff") , but I would prefer not to, because then You may have problems with date formatting and date culture.

Does anyone know how I can change the accuracy using config in NLog.config?

+6
source share
1 answer

It appears that EventContextLayoutRenderer is using Convert.ToString , which will lose the precision you are looking for:

 public class EventContextLayoutRenderer : LayoutRenderer { //.... protected override void Append(StringBuilder builder, LogEventInfo logEvent) { object value; if (logEvent.Properties.TryGetValue(this.Item, out value)) { builder.Append(Convert.ToString(value, CultureInfo.InvariantCulture)); } } } 

As you probably know (and I'm not sure how useful this is in your situation), but there is a date layout where you can specify a format and / or LongDate that will provide something like 2014-01-01 12:12:12.1234

EDIT

For what it's worth, you can easily add client layout rendering

 [LayoutRenderer("event-context-dateTime")] public class DateTimeContextLayoutRenderer : EventContextLayoutRenderer { protected override void Append(StringBuilder builder, LogEventInfo logEvent) { object value; if (logEvent.Properties.TryGetValue(this.Item, out value)) { //Your code here } } } 

And in your configuration

 <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <extensions> <add assembly="YourAssembly"/> </extensions> <targets> <target xsi:type="File" name="file" fileName="c:\temp\NlogLayout.txt" layout="${longdate} ${event-context-dateTime:item=RequestDate}" /> ... </nlog> 
+1
source

All Articles