log4j log file in user home directory

后端 未结 4 439

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:15

    Possibly the cleanest approach would be to write your log4j configuration assuming a particular system property (say myapp.data.dir)

    log4j.appender.logfile.fileName=${myapp.data.dir}/logs/myapp.log
    

    and set that property in the appropriate way in the launcher for each platform. For example if you're using an .app bundle on Mac OS X then you can set system properties in Info.plist

    
    
        
        Java
        
            
            Properties
            
                apple.laf.useScreenMenuBar
                true
                myapp.data.dir
                $USER_HOME/Library/Application Support/MyApp
    

    or set it relative to the APPDATA environment variable on Windows (which would handle the difference between XP and 7). With a Launch4J .exe you could put -Dmyapp.data.dir="%APPDATA%\MyApp" in the .l4j.ini file.

    You'd need explicit code to initialize log4j before you try and access any loggers

    if(System.getProperty("myapp.data.dir") == null) {
      // fallback to ~/.myapp (sensible Linux default) if run without a launcher
      System.setProperty("myapp.data.dir", new File(
            System.getProperty("user.home"), ".myapp").getAbsolutePath());
    }
    // ensure log directory exists
    new File(new File(System.getProperty("myapp.data.dir")), "logs").mkdirs();
    // now it's safe to configure log4j
    PropertyConfigurator.configure(this.getClass().getResource("/log4j.properties"));
    

提交回复
热议问题