log4j log file in user home directory

后端 未结 4 438

I am working on an application that will run on OSX and windows. I want the logs to be written to the users home directory. For OSX it will be under the /Users//Library/Applicat

4条回答
  •  温柔的废话
    2021-02-07 17:11

    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

提交回复
热议问题