log4j log file in user home directory

Change the ConsoleAppender to a FileAppender. As far as I know the write request will be redirected to appdata on windows OS. Not sure about MacOs.

URL mySource = MyAppMainClass.class.getProtectionDomain().getCodeSource().getLocation();
File rootFolder = new File(mySource.getPath());
System.setProperty("app.root", rootFolder.getAbsolutePath());

and edit log4j config like this

log4j.appender.NotConsole=org.apache.log4j.RollingFileAppender
log4j.appender.NotConsole.fileName=${app.root}/fileName.log

or for user home:

// log4j 1.*
log4j.appender.NotConsole.fileName=${user.home}/fileName.log
// log4j 2.*
log4j.appender.NotConsole.fileName=${sys:user.home}/fileName.log

Note that log4j 2 requires sys: prefix - thanks to @sgrubsmyon


Thank you all for the inputs. based on the hint that Alex proposed I went with the following approach,

In log4j.properties I had the following configuration

log4j.appender.FILE=org.apache.log4j.RollingFileAppender
log4j.appender.FILE.File=${userApp.root}/logs/myapp.log

and at the start of the application I have done this.

System.setProperty("userApp.root", getUserAppDirectory());

the getUserAppDirectory() method is defined as

static String getUserAppDirectory() {
    if (isMacOS())
        return System.getProperty("user.home") + "/Library/Application Support/myapp";
    else
        return System.getenv("APPDATA") + "/myapp";
}

Tags:

Java

Log4J