Logging userId in access logs

I want to log the userId in the HTTP access log. What I have in mind is:

  1. In the onRequestStart() authenticate the user and push the userId: getPageContext().getHttpServletRequest().getSession().setAttribute("username", session.userId)
  2. update the access log pattern to something like %h %l "%{username}s" %{yyyy-MM-dd HH:mm:ss.sss}t "%r" %s %b %I %D %F "%{X-Amzn-Trace-Id}i"

This is the pattern I use in Java applications, but I am not entirely sure about the request life cycle in Lucee so I don’t know if there is anything I should keep in mind. Would it be better to store the attribute on the HttpServletRequest itself instead of on the HttpSession?

We have no functionality that actually uses the username from the Java session, so even if the wrong name is present I do not think it would be a security risk.

So this worked perfectly fine in our dev environment with the code:

getPageContext().getHttpServletRequest().getSession().setAttribute("username", session.userId)

And then it didn’t work after deployment. As far as I can tell that is related to session cluster (Ortus Redis extension on Lucee 6.2.x / Java 21), because it worked with:

getPageContext().getHttpServletRequest().setAttribute("username", session.userId)

and the adjustment in the Tomcat AccessLogValve from "%{username}s" to "%{username}r".

On to the next part: is there any way I can get this into the application log if I do a simple <cflog text="Illegal error. Go straight to jail, do not pass 'Start'." /> ? We are running in Docker with LUCEE_LOGGING_FORCE_APPENDER=console.

In a clustered environment using the Ortus Redis extension, session attributes are stored in a distributed and serialized form, so they may not be immediately available to Tomcat’s AccessLogValve at the end of the request lifecycle due to session synchronization timing; therefore, session-based placeholders like %{username}s can behave inconsistently, and the correct approach is to use request-scoped attributes, ensuring reliable availability within the request, so setting request.setAttribute("username", session.userId); and using %{username}r in AccessLogValve provides consistent logging behavior.

1 Like