javaspringspring-mvctomcatspring-boot

Spring boot with embedded tomcat + access log with authentication user


I'm using spring boot with embedded tomcat + spring security. My access log from tomcat seems like this

IP - - [14/Feb/2017:08:49:50 +0200] "GET /page/2 HTTP/1.1" 200 2606

So, how can i make log file to looks like

IP - - [14/Feb/2017:08:49:50 +0200] username - "GET /page/2 HTTP/1.1" 200 2606

Every request have to have the username from which is made. For security authentication i'm using spring security with database username and password info.


Solution

  • You probably need to change access log pattern in application properties to something like this:

    server.tomcat.accesslog.pattern=%h %l %t %u "%r" %s %b
    

    where %u is Remote user that has been authenticated (see example here).


    UPD: Possibly this is not sufficient as common pattern already contains %u parameter. In this case I would recommend two additional steps:

    1. Put user's name into request session parameter, something like:

    request.getSession().setAttribute("username", user.getName());

    1. Add following parameter in access log pattern: %{username}s

      server.tomcat.accesslog.pattern=%h %l %t %u %{username}s "%r" %s %b

    which should take attribute named username from HttpSession as it described here.