Search code examples
javahibernatehibernate-envers

Hibernate Envers: Log user ip address


Im looking to log the IP address of the current user in my audit tables, currently this is done like InetAddress.getLocalHost().toString() which is wrongly logging the server IP.

Usually I could do this through autowiring an HttpRequest object but this isn't possible inside the newRevision() method I am overriding in my listener.


Solution

  • You may want to look at this post.

    In a web application, the best place for setting a ThreadLocal variable would typically be inside something like a Filter or Interceptor, basically any component-like code that runs prior to any of the web request handler's code, guaranteeing that the ThreadLocal variable has been set.

    Then you simply access that ThreadLocal inside your Envers revision entity listener and populate the custom field with the value.

    Just be sure to clear the ThreadLocal variable at the end of the request handler chain.