Reputation: 170735
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?
Upvotes: 3
Views: 127
Reputation: 70564
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.
Upvotes: 2