简体   繁体   中英

Make java logging at the same folder of the JAR

How to make java logging at the same folder of the JAR?

Thank you!

import java.util.logging.*;

public class Worker {

    private static final Logger logger = Logger.getLogger(Worker.class.getName());

    public static void main(String[] args) {

        logger.info("Logging begins...");    

         try {

             throw new Exception("Simulating an exception");
          } catch (Exception ex){
             logger.log(Level.SEVERE, ex.getMessage(), ex);
          }

         logger.info("Done...");
    }

}

Add a Handler for the Logger you're using. FileHandler is particularly good here:

Handler h = new FileHandler("my-log.log");
h.setFormatter(new SimpleFormatter()); //set format to what you normally see
logger.addHandler(h);

It will use the system property java.util.logging.SimpleFormatter.format for formatting the text, so you can either adjust the property to your use, or implement Formatter and set one yourself.

An example using the property would be:

"[%1$tH:%1$tM:%1$tS] %4$s: %5$s%n"

Which is a format I commonly see.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM