Structured Logging in Azure Application Insights

Which of the following lines, in your opinion, is a better choice for logging a trace to Azure App Insights?

var guid = Guid.NewGuid();

// Option A
log.LogInformation($"[{guid}] Start");

// Option B
log.LogInformation("[{Guid}] Start", guid); Code language: PHP (php)

I must admit that for a long time, I used the string interpolation (option A). It is concise, has no characters that would be redundant, and does the job.

But it turns out, that the option B seems to have more benefits.

Reason 1: structured logging

If we pass parameters as separate arguments, they will be conveniently available as separate properties in the logged item:

A screenshot from Application Insight Logs UI in the Azure Portal. It shows a log entry when structured logging is used in the C# code.

The application also logs the template of the log message as an independent property. It might help us a lot in writing kusto queries to retrieve the data. Queries are much simpler and more performant if we can just filter and group data by individual properties. If we don’t have such data in individual properties, we would need to parse them out from the message string. It adds complexity to queries.

Reason 2: less memory pressure

The other benefit I saw mentioned in few places is that the string interpolation (the option A) might result in more memory allocations. The impact can be significant if we have many log points. Why? The application will have to allocate memory for the combined strings, so the logger implementation gets a single string passed as an argument. But if that string will never be needed due to the later filtering by LogLevel, this is a wasted work.

The second option doesn’t have this problem because the logging library gets the template and parameters separately. Then, the library can defer combining the values into one string until it’s certain it will need it.

Tooling support

Despite those two advantages, it might look like a step back from a nice syntax provided by interpolated strings. I remember how easy it was to forget passing the correct number of arguments when we had to pass them separately from the formatting string.

Fortunately, the modern Visual Studio and ReSharper easily catch such mistakes:

A screenshot showing a fragment of C# code using structured logging. Visual Studio highlights typical errors.
Developer experience in Visual Studio 2022 with ReSharper
No comments yet, you can leave the first one!

Leave a Comment