Log Context
In gSharp, log context is an extra piece of situational information you can attach to a log entry to capture details such as identifiers, positions, or other values that describe the circumstances under which the entry was written.
You can include any data you find helpful, but context is especially valuable for repeatable operations, such as when processing items in a loop. The log context indicates exactly which iteration produced a particular log entry.
Problem Example
The following example illustrates a calculation module which iterates through the lines of a text file. Each iteration processes a single line, and if an error occurs, an exception is caught and logged. The problem is that the log entry does not include any context, so it is not clear which line caused the error:
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i];
try
{
ProcessLine(line);
}
catch (Exception ex)
{
Log.Error("ReadLineErr", ex);
}
}
Each line error will cause the same log message to be logged. The line number could be embedded into the message (or included as a structured logging property), but it is not always convenient to put the line number in the message and it would be helpful to have a clean way to do filtering or analysis.
Using a Log Context
In gSharp, a log context is any instance of the ILogContext interface. It is used by passing it to a logging method using one of the overloads that contains an ILogger argument. For example:
LineLogContext lineContext = new();
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i];
lineContext.Line = i + 1; // Line numbers are 1-based
try
{
ProcessLine(line);
}
catch (Exception ex)
{
Log.Error("ReadLineErr", lineContext, ex);
}
}
In the example above, a log context is used for each line being processed using the line number. If an error occurs, the log entry will include the context, making it easier to identify which line caused the error.
The testbed's default log format doesn't include the log context, but if you add UsingFullLogLayoutFormat() to your testbed configuration, the log context will be included in the log entry's message:
internal partial class Program
{
private static void BuildTestContext1(AssemblyBuilder builder)
{
builder
.UsingFullLogLayoutFormat()
.AddModule<GSharpTankDemo.TankVolume>(moduleBuilder => moduleBuilder
// ...
);
}
}
2026-02-27 15:07:20 [Error][Calculation.TankDemo.User][ReadLineErr] (Line 4) Invalid value 'X' was found.
When the assembly is registered with gSharp, the log context can be seen in the gSharp administration app's Server Log tab's log viewer in its own column, which can be filtered using the Log Context filter field:
The log context is actually attached to the log entry as a special structured property, which is specifically handled by the gSharp log viewer.