Nathaniel Waisbrot
Nathaniel Waisbrot

Reputation: 24483

Dynamically skipping logging messages

I have two public methods that I'd like to trace. One of the methods calls the other repeatedly. What I'd like to do is trace only the method that was called from the outside.

Here's a simple class to demonstrate what I mean:

public class LoggingExample {
    private static final Logger logger = LoggerFactory.getLogger(LoggingExample.class);
    public static final String USER_ROOT = "/home/waisbrot";

    /** could be called by fileExistsRobust *or* from outside */
    public static boolean fileExists(String filename) {
        logger.trace("Checking for file {}", filename);
        File f = new File(filename);
        return f.exists();
    }

    /** always gets called from outside */
    public static boolean fileExistsRobust(String filename) {
        logger.trace("Checking for any varient of {}", filename);
        if (fileExists(filename))
            return true;
        for (String prefix : prefixes) { // this list is 100 items long
            if (fileExists(prefix + filename));
                return true;
        }
        return false;
    }
}

Elsewhere in my code, I might call fileExists, in which case I want its logging message to get printed (assuming I'm tracing it). But if I call fileExistsRobost than I want that log message, but not fileExists.

I want to have both methods traced, but I'm getting buried in output when I call the second one. I was hoping Logback could be configured to understand what I want, but I'm not seeing anything useful in the documentation. I could flip a flag when I enter fileExistsRobust and then test for it in fileExists, but that's going to get ugly with more than one thread (since these are static methods) and it seems like it starts polluting the class with lots of logging infrastructure. I could use MDC to store the info, but that seems like an abuse of MDC.

Anyone run into this situation before? How'd you deal with it?

Upvotes: 0

Views: 179

Answers (1)

Pyranja
Pyranja

Reputation: 3589

I assume that you are able to change the code. Then the simplest way in my opinion is avoiding the problem by introducing another internalFileExists(String filename) or overloading fileExists(String filename) with a logging toogle:

public static boolean fileExists(String filename, boolean doLog) {
   if (doLog) logger.trace("Checking for file {}", filename);
   File f = new File(filename);
   return f.exists(); 
}

and let fileExistsRobust use the overloaded version with doLog = false, while the single argument version redirects to fileExists(filename, true).

That does not really address the problem, but mitigates it.

Upvotes: 1

Related Questions