0
votes

I'm currently planning a refactor of our server logging system.

I've been trying to figure out what's the best practice and design patterns to be used for logging events with the session metadata.

Among the metadata required for each log-event are:

  1. Server-side available metadata - Request's remote IP, session token etc.
  2. Client-side sent metadata - Being passed in request headers or HTTP GET/POST parameters.

The ideal situation would be that a developer would only need to pass the logger the "log message" itself, and the rest of the data will be automatically added to the log event by the actual Logger class, based on the current session/request data. (Perhaps set in the start of each servlet?)

However, doing that would mean that I'd need to update the logger state in each session request - which kind of breaks stateless-ness of the singleton Logger.

I'm writing in Java and using slf4j with log4j, into local files which are streamed into Splunk.


My initial thought was to use my own Logger utility class, which will use ThreadLocals for each of the session/client fields. These members will be initialized at the start of each session/request.

From that point, any time the logging methods are called - they will use these ThreadLocals for calling slf4j with my desired message format, together with the passed on message.


Would that design work in the long run? How else would you suggest implementing such a design? Are there any "best practices" to be aware of?

Thanks.

1

1 Answers

1
votes

I've discovered the concept of Mapped Diagnostic Context - as explained and documented here in LOG4J: http://logging.apache.org/log4j/2.x/manual/thread-context.html

That's actually a pretty similar idea to my suggestion regarding ThreadLocals, but as an out-of-the-box functionality - it's definitely the preferred option.

SLF4J and Logback provide the same functionality as well, if needed by others.