Doing structured logging with NLog in .NET core

Nlog

Structured logging has is when all the log records can be parsed easily and searched/sorted by some parameters. The data can be stored in an XML or JSON. So instead of writing a line like: [01-01-2011] debug hello 234234 we can transform this into


{
 "time": "01-01-2011",
 "level": "debug",
 "msg": "hello",
 "transaction": "234234"
}

So how do we do this with .NET core? First, we use the default Microsoft ILogger mechanism and we use placeholders for logging like this:


string transaction = Guid.NewGuid().ToString("N");
DateTime endTime = DateTime.Now;

logger.LogDebug("My transaction: {transaction} lasted until {endtime}", transaction, endtime);

//Instead of 

logger.LogDebug($"My transaction: {transaction} lasted until {endtime}");

Then in the nlog.config file do this:


<target name="fileTarget"
	type="File"
	fileName="log.txt"
	archiveFileName="log.{#}.txt"
	archiveEvery="Day"
	archiveNumbering="Rolling"
	maxArchiveFiles="7" >
	<layout type="JsonLayout">
		<attribute name="time" layout="${longdate}" />
		<attribute name="level" layout="${level}" />
		<attribute name="message" layout="${message}" escapeForwardSlash="false" />
		<attribute name="transaction" layout="${event-properties:transaction}"/>
		<attribute name="endtime" layout="${event-properties:endtime}" escapeForwardSlash="false"/>
				
		<!--<attribute name="eventProperties" encode="false" >
			<layout type='JsonLayout' includeAllProperties="true" includeEventProperties="true"  maxRecursionLimit="2"/>
		</attribute>-->
	</layout>
</target>

Post a Comment

Previous Post Next Post