Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Providing logging (debug) context

I have an application that uses several different Java classes and would like to be able to supply debugging context to logging messages.

This (application and data-specific) context (basically, a string) will be constructed or retrieved somehow by each class individually and will be passed to the appropriate logging call, e.g.

logger.debug(context + ", whatever error message");

So, my question is, what would be the best pattern to use in order to implement this functionality across the application?

I am thinking of having all classes that need to support context-sensitive logging implement a Java interface with a few appropriate methods, e.g.

public interface ContextSensitive
{
    public String getContext();
    public String setContext();
}

where the setContext() method will be useful for cases where an object (say) secondObject is instantiated from an object (say) firstObject that has context, but secondObject has not. So, firstObject would also do something like

secondObject = new SecondObject();
secondObject.setContext(context);

Does the above make sense, or should I do something better?

An alternative I have been considering is to write a wrapper around the logging library to offer this functionality, but I don't see any value to this approach, compared to the one I described above, based on the ContextSensitive interface.

If there are any examples of open source projects that had to tackle the same issue, I would appreciate a link.

Many thanks!

like image 569
PNS Avatar asked Jan 19 '26 14:01

PNS


2 Answers

I suspect you are looking for something similar to MDC (mapped diagnostic context) which is a feature of log4j, logback and slf4j frameworks. The context can be set only once before the method call and then logging framework can be configured to produce logging messages including fields from the context.

like image 138
Andrey Adamovich Avatar answered Jan 21 '26 07:01

Andrey Adamovich


This is a perfect example of a cross-cutting concern, so use AOP.

like image 32
DaveFar Avatar answered Jan 21 '26 07:01

DaveFar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!