4

I created a command line tool that ships as an executable jar. When someone uses my tool I do not know where the jar will be located. All of the logging is being done with logback. I want my log file to go to the same directory as the jar file no matter where the jar is located and no matter what the current directory is.

My current logback.xml files looks like this.

<configuration>
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>admintool.log</file>
        <encoder>
            <charset>UTF-8</charset>
            <pattern>%d{"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"} [%thread] %-5level %logger{35} - %msg %n</pattern>
        </encoder>
    </appender>

    <root level="debug">
        <appender-ref ref="FILE" />
    </root>
</configuration>

Does anyone know how I can get the log to go where the jar is? Thanks in advance.

user3108671
  • 83
  • 1
  • 2
  • 10

1 Answers1

4

There is a way to provide property values to Logback configuration during runtime:

http://logback.qos.ch/manual/configuration.html#definingPropsOnTheFly

You need to create a class that implements PropertyDefiner interface and returns location of the jar

public class MyPropertyDefiner extends PropertyDefinerBase {
    @Override
    public String getPropertyValue() {
        return MyPropertyDefiner.class.getProtectionDomain().getCodeSource().getLocation().getFile();
    }
}

In your logback.xml you can specify something like this

<configuration>
    <define name="jarLocation" class="MyPropertyDefiner"/>
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>${jarLocation}</file>
        ...
    </appender>
    ...
</configuration>
ponomandr
  • 1,523
  • 13
  • 21