Java implementation for tracking trace on errors

This blog post describes an interesting approach to posting:

When activated, if an exception is thrown (for example, a NullPointerException exception), in addition to the stack trace, a full trace of the session to this point is displayed. It works by starting a registration session for each session, but only outputting the result if an exception occurs.

Is there an implementation in any Java logging framework?

+3
source share
1 answer

Not that I know, but it is entirely possible to write a custom appender that delegates the corresponding session log. For Logback, it could be something like this:

class SessionLogAppender implements Appender<ILogEvent> {
    private static final TheadLocal<Object> sessionHolder = new ThreadLocal<Object>();

    private Map<Object, SessionLog> sessionLogs = new ConcurrentHashMap<>();

    /** must be invoked when a new session begins */
    public static void begin(Object session) {
        sessionHolder.set(session);
    }

    /** must be invoked when a session ends */
    public static void end() {
        Object session = sessionHolder.get();
        writeIfNecessary(sessionLogs.get(session));
        sessionLogs.remove(session);

        sessionHolder.clear();
    }

    @Override
    public void doAppend(ILogEvent e) {
        Object session = sessionHolder.get();
        SessionLog l = sessionLogs.get(session);
        if (l == null) {
            l = new SessionLog();
            sessionLogs.put(session, l);
        }
        l.append(e);
    }
}

, .

+2

All Articles