Categories
Technology

Get Some Structure

It is important to move on from good ole’ comfort food, Console.WriteLine() for everything. When you are first learning how to create a .NET application, inside your Main method is a Console.WriteLine() that system outputs to the console.

This is standard C# code inside your first dotnet console application.

But that isn’t a best practice as you begin to develop production ready applications.

Let’s dig into this a little deeper. Why is this even important? What is the difference between structured and unstructured logging?

Serilog is a .NET library that takes advantage of structured event logging. And structured logging provides features like logging levels, uniform formatting, timestamps, and the ability to direct those log messages to the right place (Datadog or Splunk for example). You can configure and enrich the logs that you receive from your applications and provide insights on things like: storing properties associated with logging events, with Serilog we have access to the log level: logging information (describing things happening within the application like logging large sql queries before they begin), alerts (like exceptions being thrown), and fatal application errors that would cause the application to completely fail.

Printing out a for loop from 0 to 9 showing here the timestamp, log level, and message template

This logging gives more visibility into the health of our applications proactively so you don’t have to wait for bug tickets/ alerts to come through to assess health in various areas of the application. Human readable logs are great for triaging issues we have never seen before or unintended paths in the codebase that you can get ahead of by automating responses based on enriched structured logs from your application.

You can browse and install Serilog as a nuget package for your dotnet application:

You can enrich your logging to output in json format with: new JsonFormatter() within the console output configuration, for example:

Inside your Class, you will need to create your logger (this is specifically for console applications where it is not as simple to use dependency injection). Here is a way to create your static logger and reference your logger within a try catch:

Structured logging offers a set of features that provide important information about the health of your applications and where things may be breaking, far superior to standard unstructured logging output when using Console.Write() or Console.WriteLine() for example.

Resources mentioned in this article:

Dale Yarborough

By Dale Yarborough

I am a Software Engineer at General Motors and Appalachian State University Alum. Previously: Whole Foods Market IT, Charles Schwab