Logging to Splunk from AWS Lambda via NLog

First, it’s important to keep you Lambdas lean and mean as warm up times can be significant (in seconds!). Do not load unnecessary libraries like ASP.NET Core in your Lambda functions.

I’ll be showing how to use NLogTarget.Splunk package from NuGet (link).

Just like for any other type of app, you need an NLog.config file (see example here)

I strongly recommend you enable async logging in NLog.config via

targets async="true"

otherwise logging will be done synchronously, slowing down the execution time of your function.

To load NLog.config, do the following in the beginning of your function:

var logFactory = LogManager.LoadConfiguration("NLog.config");
var logger = logFactory.GetCurrentClassLogger();
// continue on using logger. LogManager.GetCurrentClassLogger() also works

NLog.config must be in your Lambda package, so ensure it’s copied there upon build (set it as “Content/Copy If Newer” in Visual Studio)

Prior to completing your Lambda’s execution, ensure you add

LogManager.Flush(new TimeSpan(0, 0, 3)); // flush any remaining messages. Max 3 seconds

This will allow NLog to “catch up” writing any outstanding log entries. If you have a global exception handler in your lambda function, make sure to add the same line there as well. If you do not — you may have a lambda that fails and no logs that are sent out.

That’s it. To learn more about using NLogTarget.Splunk, see documentation here

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s