1

I have built a java application and I've been using slf4j/log4j for logging. I would now like to provide the user with the possibility of changing logging levels without needing to re build the .jar file.

I've read around that to do this your properties file needs to be inside of the classpath of the application. I've tried using the Class-Path header in the MANIFEST.MF file to achieve this, however it is not working.

These are the two examples I've tried.

Class-Path:./config/
Class-Path:C:/users/user/directory/tools/config/

However none of these seem to be added to the classpath as I've tried printing its contents once the application starts running.

Moises Jimenez
  • 1,962
  • 3
  • 21
  • 43

2 Answers2

0

As suggested by this question, I ended up adding a parameter to the java execution command. Bear in mind that if you execute through bash commands, as I do, you need to add the full path to the directory.

java -Dlog4j.configuration=file:/path/to/log4j.properties -jar myApp.jar

I don't like this since it makes it extremely dependent on path configuration but it will suffice.

Community
  • 1
  • 1
Moises Jimenez
  • 1,962
  • 3
  • 21
  • 43
0

Please find below a list of possible solutions.

1) java -jar myApp.jar will search for the log4j.properties in following order

  • root of myApp.jar
  • the directories specified in the header Class-Path: of the myApp.jar

2) java -Dlog4j.configuration=file://path/to/file//log4j.properties -jar myApp.jar will use the properties file specified by -Dlog4j.configuration=...

3) java -Xbootclasspath/a:../config -jar myApp.jar will search for the log4j.properties in following order

  • directory ../config/
  • root of myApp.jar
  • the directories specified in the manifest header Class-Path: of the myApp.jar

I believe solution 1) should solve your problem like following

  • make sure there is no log4j.configuration in the root of myApp.jar
  • the manifest header contina for example Class-Path: config/
  • and the directory structure of your installation is
    ./myApp.jar
    ./config/

edit A possibe solution to avoid the hardcoded path, but use a defined location for the log4j.properties file could be as below.

assume following structure of your application

c:\somewhere\myApp.jar
c:\somewhere\config\log4j.properties
c:\somewhere\run_myapp.cmd

run_myapp.cmd

@echo off
... do your necessary preparation here
java -Dlog4j.configuration=file:%~dp0log4j_2.properties -jar myApp.jar

This will use always the config\log4j.properties relative to your myApp.jar.

%~pd - expands to drive letter and path of run_myapp.cmd

With this solution your users need to store the properties file at the given place but don't need to change the run_myapp.cmd script.

SubOptimal
  • 22,518
  • 3
  • 53
  • 69