Setting java.util.logging destination programmatically
Asked Answered
T

2

9

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.

Thickknee answered 4/8, 2009 at 12:41 Comment(0)
N
9

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!");
Nosing answered 26/5, 2010 at 18:54 Comment(0)
D
1

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.

Doan answered 4/8, 2009 at 18:5 Comment(1)
(nb: this answer was for the original, unedited question "Setting JUL logging" / "I'm using JUL logging...") Instead of Log4j, this could be achieved using Logback (use slf4j to redirect all logging to logback); see #3803684 (but still, it's a bad idea; there are various logback appenders/policies that control the output file, allowing the log configuration to stay in the xml config, where it belongs)Aurelie

© 2022 - 2024 — McMap. All rights reserved.