Disclaimer: I am a consultant at Amazon Web Services, and this is my personal blog. The opinions expressed here are solely mine and do not reflect the views of Amazon Web Services (AWS). Any statements made should not be considered official endorsements or statements by AWS.
In this post, you will learn how you can use Structured Logging with NLog in your AWS Lambda using .NET Core.
You will also learn, how you can use AWS CloudWatch Log Insights to query the log data to see how structured logging is beneficial to you.
Open Visual Studio, create New Project, and select AWS Lambda Project (.NET Core - C#).
Next, from the available blueprints, select the Empty Function.
In Traditional Logging, you simply combine both the event-information and event-properties together in a single text message.
But when using Structured Logging, both event-information and event-properties are stored in a particular format such as JSON, XML or CSV, so that these logs could be queried easily at a later point in time.
Let's examine the output for the below example:
The output will be formatted as:
Here you can see, both event-properties
and event-information
are bound together in a single text message. We are considering orderId
& user
as event-properties in this example.
The output will be formatted as:
Here you can see, the entire event has been logged as a JSON document, where both event-properties
and event-information
are separate from each other. This separation helps you in query event logs at a later point in time.
Install NLog.Extensions.Logging
NuGet package.
Create a nlog.config
file, and set Copy to Output Directory to Copy always.
Copy below content in nlog.config
file.
Above nlog.config
file includes mainly 2 things - Target & Rules.
For Lambda, writing to the console is sufficient as Lambda will automatically move console logs to AWS CloudWatch Log Group.
In nlog.config
, we used JsonLayout
for structured logging, otherwise, we could have used a normal layout as shown below.
Go to csproj
file and add below NuGet packages.
Build the project to restore all the NuGet packages.
Go to Function.cs
file, and add the following namespaces.
Update the content of Function.cs
file as per below.
Here, you can see in ConfigureServices
method, we have first removed all the existing logging providers and then added the NLog provider to LoggingBuilder
object.
Now, build and run the function locally using Visual Studio.
See the output on local.
See the output for structured logging in AWS CloudWatch Logs.
Next, go to AWS CloudWatch, and select Logs Insights.
Select the Log Groups from the dropdown and write a query to filter logs.
See the below screenshot of the filtered logs in AWS CloudWatch Logs Insights.
In this post, we explained how you can use NLog to write structured logs in AWS Lambda using .NET Core. Please let me know your thoughts and feedback in the comment section below.
Thank You ❤️