Setting java.util.logging destination programmatically

≡放荡痞女 提交于 2019-12-10 12:48:22

问题


I'm using java.util.logging for logging and tracing purposes. How can I within a Java application dynamically set the file to which the log should be written.


回答1:


The java.util.logging.FileHandler might do its job for you. The following code snippet shows a simple example how to do set the logging destination programmatically:

    Logger logger = Logger.getLogger("my.logger.name");
    try {
        FileHandler handler = new FileHandler("application.log", true);
        logger.addHandler(handler);
    } catch (IOException e) {
        throw new IllegalStateException("Could not add file handler.", e);
    }
    logger.info("Hello Logger!");



回答2:


Are you talking about JULog?

If so, the answer is "you can't". In order to change what file you're logging to (or change anything else in configuration) you need to know what underlying logging implementation you are using and the whole point of using JULog (quite arguable, btw, unless you're developing a library) is to not have ANY ties to logging implementations.

If selecting a file at runtime is a requirement you're likely going to be better off going with a concrete implementation like Log4j.



来源:https://stackoverflow.com/questions/1227292/setting-java-util-logging-destination-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!