PostSharp6.4/Logging/Adding Custom Log Records Manually/Adding Properties to Messages and Activities

Adding Properties to Messages and Activities

When you write a message, open an activity, or close an activity, you can specify additional properties. Properties are name-value pairs that are passed to the logging backend. Unlike message parameters, properties are not rendered into the message text. When defined on activities, properties are inherited by children contexts and activities.

This topic contains the following sections:

Defining a property

Every method that allows you to write a message, open an activity, or close an activity accepts an optional parameter named options. This object has a property named Properties. For instance, the LogLevelSource.Write<T>(T, WriteMessageOptions) method accepts an options parameter of type WriteMessageOptions, and this type has a Properties property.

To add a property to a message or an activity, assign the Properties property to an array of LoggingProperty instances. A LoggingProperty is basically a name-value pair enhanced with a few options.

C#
logSource.Default.Write( Formatted( "Hello, World." ), 
                         new  WriteMessageOptions { Properties = new [] { new LoggingProperty( "User", User.Identity.Name ) } });
Late evaluation of properties

Since properties added to activities apply to children activities and messages by default, there can be some time between the moment the user code instantiates a LoggingProperty and the moment the property is emitted to the back-end. Sometimes, it is desirable to evaluate a property exactly at the moment when the property is being written to the back-end.

Example

The following code opens an activity and defines a property named Culture, which should be evaluated to the current culture of the user. Since the user can change the culture during the activity, the property must be evaluated dynamically.

C#
using ( var activity = logSource.Default.OpenActivity( Formatted( "Opening MainWindow" ), 
                                new  OpenActivityOptions { Properties = new [] { new LoggingProperty( "Culture", () => CultureInfo.CurrentCulture.Name ) } }) )
{
     // Long-running operation.
}
Inheritance of properties

Activity properties are inherited by default, which means that the property will be added to any child activity or any message within this activity. To disable inheritance, set the IsInherited property to false.

Property inheritance works even when the activity is hidden because of low verbosity.

Note Note

As a side effect of property inheritance, the OpenActivity<T>(T, OpenActivityOptions) method always opens an activity when it has at least one inherited property, even if the level of the open message is too low to be emitted.

Other properties of LoggingProperty

The LoggingProperty class has several properties useful when logging distributed systems. See Implementing Logging for a Distributed System for details.