Search code examples
javalogback

Adding a version number marker to logback log with minimal code changes


I am attempting to add an application "version" number to the beginning of each log line. In my reading I noticed that "Markers" are what I appear to need.

In code I am using @Slf4j which is returning the ch.qos.logback.classic.Logger and throughout the code it is being used simply as log.info("Hey Bob"). How would I go about pre-pending the Marker (log.info(VERSION_MARKER, "Hey Bob")) to every log statement without affecting the existing code?

I don't/can't go through thousands of lines of code and make the changes.

Or, is there a better way to do this?

<appender name="LOGSTASH" class="ch.qos.logback.core.rolling.RollingFileAppender">
   <append>true</append>
   <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
      <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %m%n%wEx</Pattern>
   </encoder>
</appender>

So my assumption is to modify the Pattern above.


Solution

  • You can use system properties in your pattern, e.g. %property{app_version}

    <Pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %property{app_version} %m%n%wEx</Pattern>
    

    When you run your app, add -Dapp_version=1.2.3 to the command line.

    You can also programmatically call System.setProperty("app_version", "1.2.3"), but depending when that's called, some things may have already been logged before that.

    https://logback.qos.ch/manual/layouts.html#property