开发者

Could you suggest me a pattern to log exceptions during java application lifecycle?

I want to use the simple java.util.logging.* package to log exceptions. Any suggestions, links, a开发者_开发知识库rticles to do this in a basic but elegant way? I should implement it in a Java EE application.

I was thinking to a singleton class... what do you think?


The following doesn't handle the case of logging all exceptions automatically but might get you closer. At my current company we extended Exception with a CompanyException that supported a list of callbacks. Something like:

public abstract class CompanyException extends Exception {
    private static final List<ExceptionCallback> callBacks =
            new ArrayList<ExceptionCallback>();

    public CompanyException(String message) {
        super(message);
        invokeCallbacks();
    }

    // register class to be called whenever exception is constructed
    public static void registerCallback(ExceptionCallback callback) {
        // we expect the registers to be done long before the first exception thrown
        List<ExceptionCallback> newCallbacks = new ArrayList<ExceptionCallback>();
        newCallBacks.addAll(callBacks);
        newCallbacks.add(callback);
        callBacks = newCallBacks;
    }

    private void invokeCallbacks() {
        for (ExceptionCallback callBack : callBacks) {
            try {
                callBack.exceptionConstructed(this);
            } catch (Throwable th) {
                // ignore it because we can't go recursive 
            }
        }
    }
}

The callback was a simple interface:

public interface ExceptionCallback {
    public void exceptionConstructed(Exception exception);
}

Then all of our internal exceptions would throw these or rethrow/wrap external exceptions. We then would register a logging class which could log exceptions using log4j or our internal logging mechanisms. Obviously the exception could do the logging itself but we wanted the separation. Our logger had a dedicated thread to do it in the background and send it to the central logging server. You need to be very careful about recursion if you throw while you are logging.


You can take a look at Base 22's logging suggestions, they're pretty basic but they cover a basic set of standard logging functionality.

I discourage the use of a Singleton, as with a modern logging framework you don't need them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜