How to configure logging when running a JAR?

前端 未结 3 978
一整个雨季
一整个雨季 2021-02-14 14:15

I am new to Java logging API and need some help with this problem: While creating the application, my config file was stored in the project root folder, so I used -Djava.u

相关标签:
3条回答
  • 2021-02-14 14:24

    The javadoc says:

    In addition, the LogManager uses two optional system properties that allow more control over reading the initial configuration:

    "java.util.logging.config.class"
    "java.util.logging.config.file" 
    

    These two properties may be set via the Preferences API, or as command line property definitions to the "java" command, or as system property definitions passed to JNI_CreateJavaVM.

    If the "java.util.logging.config.class" property is set, then the property value is treated as a class name. The given class will be loaded, an object will be instantiated, and that object's constructor is responsible for reading in the initial configuration. (That object may use other system properties to control its configuration.) The alternate configuration class can use readConfiguration(InputStream) to define properties in the LogManager.

    So, either use the java.util.logging.config.file system property, and store the config file out of the jar file (which is probably a good idea if you want to be able to customize the logging properties in order to debug or analyze some weird behavior), or store the config file wherever you want (in the jar file, for example), and use the java.util.logging.config.class system property to load and instantiate a class that will read the file in the jar file (Using Class.getResourceAsStream()).

    0 讨论(0)
  • 2021-02-14 14:44

    You can't specify JVM arguments into the MANIFEST.MF file so you have to specify the logging properties at the command line or with a shortcut :

    java -Djava.util.logging.config.file=logging.properties -jar yourjar.jar
    

    Otherwise you could package a properties file(logging.properties in your case) in the JAR, read that at startup and put those settings into the system properties.

    0 讨论(0)
  • 2021-02-14 14:46

    I know it's little late to answer this question but I ran into this issue few days back with the runnable jar and I solved it like this:

    java -Djava.util.logging.config.file=logging.properties -cp test.jar com.sample.test.Main

    where test.jar is the name of your jar and com.sample.test.Main is the fully qualified name of your main class.

    0 讨论(0)
提交回复
热议问题