How to set log4j2 log file directory to always use the app directory?


This is not JME-related, but I hope someone can help me with this issue :slightly_smiling_face:

My log4j2.xml file is configured to use the rolling file to save the log file. (I think I copied it from one of the Simsilica libraries.)

        <RollingFile name="RollingFile" fileName="model-converter.log" ignoreExceptions="false"
                <Pattern>%d{ABSOLUTE} %t %-5p [%c] %m%n</Pattern>
            <OnStartupTriggeringPolicy />

when I run the app from the /bin directory, the log file will be placed in there (bin/logs) but if I create a Linux launcher (something like a desktop shortcut in windows) and run it via launcher from the Desktop then the log file is saved inside my user home directory (home/ali/logs).

Looks like it uses the “user.dir” system property to locate the log file location. How can I config it so it always generates the log file inside the application root?
Note that I do not want to config it with an absolute path in a properties file after distributing the app.

I already searched the web but still, I couldn’t get the answer I wanted. Will still keep looking through though, just thought I might get to answer quicker if I ask here :slightly_smiling_face:

Thanks in advance

I don’t think you are going to be able to do this just from the configuration file.

If you’re willing to approach this programmatically:

  1. Right at startup, before anything else, detect the location that your app is living at. This can (usually) be done by <ClassName.class.getResources("/PackageName/ClassName.class") for a class that you know is loaded. (Usually the class that is running the code.) This should point you to the absolute location of the jar file, and you can then walk to construct a File object to where you want the logs to go. I’ll leave the needed try blocks and error-catching as an exercise for the reader.
  2. Configure logging programmatically for log4j2, passing the above-constructed File object. This may actually be the harder part, as some people claim that log4j2 is “allergic” to being configured through the API.
1 Like

Thanks, going to try that approach.

In all cases, that config is using the current working directory. When you run the app from bin then bin is the current working directory. When you run the app from your desktop them your home is the current working directory (it may even say so in the shortcut properties).

I’ve never looked at pinning it to the app location before.

1 Like

It’s worth saying that this approach may have permissions problems. E.g. if the user puts your application in program files your application may not have write permission to its own directory


true, but also please note, a lot of games(AAA/AA) store logs in game dir.

some directly, others in /bin in game dir, some have /logs somewhere in game dir too

1 Like