Search code examples
c#.netloggingsolid-principles

How can I implement library level tracing and diagnostics in a SOLID manner in .NET?


When creating enterprise libraries designed for reuse in a larger scope, I often find myself freezing up over implementing cross-cutting design concerns as these can be really hard to get right. Today I'm stuck on analyzing the best way to do tracing and diagnostics within a reusable enterprise library.

Looking around at .NET's BCL, it seems that logging and diagnostics is a non-trivial chunk of the framework.

  • System.Diagnostics has the Trace family of types, used for execution tracing, and having app.config friendly sourcing and subscription (for listeners.) With that being said, I tend to hate app.config in general, and rather avoid the loosely typed arcaneary that comes with magic configuration strings.

  • System.Diagnostics.Tracing has the EventSource family of types, used for Event-based diagnostics. This is more my type, but it isn't clear to me if and how this should be used in libraries as logging policy is a concern of the application more than the domain libraries.

One possibility that makes sense to me is to simply define in my foundation domain library some common logging interfaces, and allow applications to inject implementations via some sort of ambient context pattern, but defining my own logging types for this seems unnecessary.


Solution

  • One possibility that makes sense to me is to simply define in my foundation domain library some common logging interfaces.

    This is correct. Also you must create a default logger implementation which may target to e.g. System diagnostics trace class (in case tracing is turned on by consumer app of this library).

    allow applications to inject implementations via some sort of ambient context pattern

    Instead of struggling on how others will inject the logger simply provide a way e.g. custom factory to inject the implementation of logger interface.

    The factory will be responsible for supplying the instance in Library. If a implementation is provided then use that otherwise the default instance shall be used as default logger. You can take a look at the EF7 library(logging) for infrastructure of logger.