Operation context represents a hierarchy of logical operations or steps in application code flow (handling a query, sending a request, performing an iteration of a periodical process).
Unlike source context, operation context is bound to current ExecutionContext and can be manipulated independently of any log instances.
Operation context is maintained by defining named scopes that represent logical operations.
​
Structure
Like source context, operation context is also hierarchical. Nested operation scopes produce a stack-based sequence of contextual values:
1
// current operation context is null
2
using(newOperationContextToken("op1"))
3
{
4
// current operation context is ["op1"]
5
using(newOperationContextToken("op2"))
6
{
7
// current operation context is ["op1", "op2"]
8
using(newOperationContextToken("op3"))
9
{
10
// current operation context is ["op1", "op2", "op3"]
11
}
12
// current operation context is ["op1", "op2"]
13
}
14
// current operation context is ["op1"]
15
}
16
// current operation context is null
Copied!
​
Implementation details
Operation context is implemented as an extension over log interface. It can be enabled as follows:
1
log = log.WithOperationContext();
Copied!
Returned log instance will enrich incoming log events with a special well-known OperationContext property whose value is represented by OperationContextValue class.
Context scopes are started by constructing OperationContextTokens and ended by disposing these tokens.
​
Rendering in text-based logs
Here's an example of how text-based logs render operation context:
1
var log =newSynchronousConsoleLog().WithOperationContext();
2
​
3
using(newOperationContextToken("op1"))
4
{
5
log.Info("Message 1");
6
​
7
using(newOperationContextToken("op2"))
8
{
9
log.Info("Message 2");
10
​
11
using(newOperationContextToken("op3"))
12
{
13
log.Info("Message 3");
14
}
15
}
16
}
Copied!
Sample output from this code:
1
2019-03-10 01:30:06,727 INFO [op1] Message 1
2
2019-03-10 01:30:06,761 INFO [op1] [op2] Message 2
3
2019-03-10 01:30:06,762 INFO [op1] [op2] [op3] Message 3