0

I have added Logger in my code at serveral places (Log4j). Like Logger.info(" some thing "); My log is something like this at so many places,

Timestamp LogLevel SometText SomeMoreText

Whenever any new request comes, I want to add some value like ID:CurrentValuetime in every logLevel which will be same till the request is there to all LogLevel so my logs should be like

Timestamp LogLevel ID:CurrentValuetime SometText SomeMoreText

ID:CurrentValuetime Should be same at all places it should be global and final which should get appended automatically to all loglevel

How can I achieve this ?

  • The logger needs to be configured. By configuration, you can configure an log formatter which contains you time stamp an log level where you want. https://logging.apache.org/log4j/2.x/manual/configuration.html Your explanation about "ID:CurrentValuetime" I don't understand. What is "ID:CurrentValuetime"? – Maik May 25 '21 at 05:33
  • 1
    Regarding the "CurrentValuetime", you can use the MDC for that. You could register a servlet filter that sets a value in the MDC and extend the log pattern to include that value from the MDC. See [Improved Java Logging with Mapped Diagnostic Context (MDC)](https://www.baeldung.com/mdc-in-log4j-2-logback#mdc-in-log4j) or search for MDC. You will probably find more info when searching for "correlationId mdc". – Ken S May 25 '21 at 05:55

1 Answers1

1

Achieved it with the help of MDC

Created a servlet filter and with the help of

 MDC.put("UniqueID", UIDValue);

I was able to add unique value into log at once.

try {
             chain.doFilter(request, response);
            } finally {           
                MDC.remove("UniqueID");
              }

And remove value once request is complete