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!