If the logging framework supports injecting additional data at log entry creation time then - look at the Application Insights integration code.

If the logging framework doesn’t support injecting additional data - have a look at CorrelatorSharp.Logging.

Why?

Creating a log entry (logger.LogTrace("something")) and actually persisting it are separate operations which can execute in different contexts (threads or processes). We do need to capture the current activity info at the point of creating the log entry and unfortunately frameworks such as NLog doesn’t expose a generic way to do that.

To workaround this limitation CorrelatorSharp.Logging provides an ILogger and LogManager which are practically equivalent to what you will find in most logging frameworks and introduces an adapter model. This enables dropping in Correlatorsharp.Logging and removing direct references to e.g. NLog without having to do code changes other than a namespace change.

For further information: CorrelatorSharp.

Get it

Where What
NuGet CorrelatorSharp.Logging
Latest Build (master) Build status

Implementing a CorrelatorSharp.Logging adapter

Tip: Havea look at the NLog adapter for an example.

  1. Implement the ILogger interface and use ActivityScope.Current to capture the current activity scope’s correlation id.
  2. Implement the ILogManagerAdaptor to create ILogger-s.
  3. Add a UseXXXXX extension method on LoggingConfiguration to enable users to configure CorrelatorSharp.Logging to use your framework.
public static LoggingConfiguration UseNLog(this LoggingConfiguration config)
{
    config.WithLogManager(new MyNewLoggingFrameworkLogManagerAdaptor());
    return config;
}