Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java implementation of trace-on-error logging

This blog post describes an interesting approach to logging:

When activated, if an exception (e.g. a NullPointerException) is thrown, the complete trace of the session up to that point is output, in addition to the stack trace. It works by starting session logging for every session, but only outputting the result if an exception occurs.

Is there an implementation of it in any Java logging framework?

like image 914
Alexey Romanov Avatar asked Sep 15 '26 15:09

Alexey Romanov


1 Answers

Not that I know of, but it's quite possible to write a custom appender that delegates to the respective session log. For Logback, this could be something like:

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);
    }
}

This assumes that each session is handled by a dedicated thread.

like image 120
meriton Avatar answered Sep 18 '26 18:09

meriton



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!