Skip to main content

Structured Logging

Structured logging is a powerful technique that allows developers to log data in a structured format, making it easier to analyze and query logs. While the message in a log entry is human-readable, the structured data is added to make the log more machine-readable, which enables advanced log analysis and monitoring capabilities.

Example​

Consider a simple, contrived log entry that contains a message indicating the length of a call to api.open-meteo.com:

14:20:27 [Info] API call to https://api.open-meteo.com/v1/forecast completed in 1.237s.

The message is human-readable and provides some information about the API call, but it is not easily queryable. If you wanted to analyze the performance of this API call over time, you would need to parse the message to extract the URL and the duration, which can be error-prone and inefficient.

With structured logging, the https://api.open-meteo.com/v1/forecast is attached to the log entry as a named property, such as ForecastUrl, and the 1.237 is attached as another named property, such as Duration. This way, you can easily query the logs for all entries with a specific ForecastUrl or analyze the duration of the API call over time without needing to parse the message.

Structured Logging in gSharp Modules​

Structured logging is supported in your gSharp calculation module via the Log property on the base class of your module class (see Writing Log Entries).

Without structured logging the above example log entry would likely be written using string interpolation like this:

string url = getUrl("forecast");
Stopwatch stopwatch = Stopwatch.StartNew();
GetForecast(url);
stopwatch.Stop();

Log.Debug("meteofc", $"API call to {url} completed in {stopwatch.Elapsed.TotalSeconds:0.000}s.")

The call to Log.Debug() writes the url and duration directly into the message, as

API call to https://api.open-meteo.com/v1/forecast completed in 1.237s.

which is easy for humans to read, but not so easy for machines to analyze.

Using structured logging the log entry is constructed by separating the message from the data, like this:

Log.Debug(
"meteofc", "API call to {ForecastUrl} completed in {Duration:0.000}s.",
url, // ─────────────────────┘ │
stopwatch.Elapsed.TotalSeconds) // ─────────────────────┘

In this example, the URL and duration which were previously embedded in the message are now referenced in the message by named placeholders {ForecastUrl} and {Duration:0.000}. The values themselves are passed as additional parameters to the Log.Debug() method. Those values are matched to the names in the message by their relative positions.

The message still contains the URL and duration for human readability, as it did before, but now the log entry also contains structured data that can be easily queried and analyzed. Here is an example of the structured data (rendered as JSON):

{
"ForecastUrl": "https://api.open-meteo.com/v1/forecast"`,
"Duration": 1.2369411
}

There must be a 1-to-1 relationship between the format items in the message and the additional arguments passed to the logging method. Mismatched items may not be logged correctly or at all.

note

The {Duration:0.000} format item in the message includes an optional format specifier :0.000 which formats the duration using the same formatting rules as standard .NET string interpolation. The actual value passed as an argument is the full precision of stopwatch.Elapsed.TotalSeconds, which is stored as a double in the structured log data.

Additional Data​

There may be times when you want to include additional data in a log entry that is not easily represented in the message, such as a complex object or a collection of values. In these cases, you can attach this data as additional properties to the log entry using tuples of type (string, object). The first tuple argument is the name of the property, and the second argument is the value.

These tuples are passed to the logging method as arguments after all of the named arguments. In the following example, an array of codes is attached to the log entry as a property named Codes:

string[] codes = FindCodes();
Log.Info("{Count} codes found", codes.Length, ("Codes", codes));

The list of codes is not included in the message, but it is attached to the log entry as a structured property named Codes, which can be queried and analyzed separately from the message.

The list of codes could have been included in the message by converting it to a string using a {Codes} format item and string.Join(), but that would make it less useful for analysis. Instead, the codes would be embeded using standard string formatting methods (such as string interpolation) in conjunction with the string.Join(), and attach the actual array as structured data for analysis.

string[] codes = FindCodes();

Log.Info($"{{Count}} codes found: {string.Join(", ", codes)}",
codes.Length,
("Codes", codes));

In this example, the $"" string interpolation produces a format message like:

"{Count} codes found: A1, B2, C3"

where the list of codes is human-readable. The codes.Length is passed as an argument that matches the {Count} format item in the message, and the actual array of codes is attached, via the extra tuple argument ("Codes", codes), as a structured property named Codes for analysis.

info

Logging is supported by gSharp using NLog, which is where the support for structured logging is implemented. For detailed information about NLog's structured logging capabilities, see the NLog documentation.

Property Data​

The gSharp administration app's log viewer currently does not support filtering and analysis of structured log data. However, the structured data is included in the database log entry (the gSharp logging database) as JSON, which is fully supported for querying and analysis using SQL Server's JSON functions.

The log entry for the examples in this section would have the following JSON stored in the database log entry's Properties column:

{
"Url": "https://api.open-meteo.com/v1/forecast",
"Duration": 1.2369411
}

{
"Count": 3,
"Codes": ["A1", "B2", "C3"]
}

In addition to gSharp's default logging targets of file and database, other logging targets can be added to gSharp, such as third-party log aggregation or observability platforms that support structured log data. These additional targets can help you take full advantage of structured logging's capabilities.

NLog provides a comprehensive list of supported targets which can be used with gSharp. Contact gSharp support for more information about how to add them.

See Also​