简体   繁体   中英

Log console output to a log file Java logger

I am trying to write all my console output to a log file using the Java Logger class.

public static Logger logger = Logger.getLogger("Log");  
public static FileHandler fh; 
public static ConsoleHandler handler = new ConsoleHandler();
public static DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
public static Calendar cal = Calendar.getInstance();

/**
 * Launch the application.
 * @param args
 * @throws IOException
 */

/* -- START MAIN -- */
public static void main(String[] args) throws IOException {
    Settings.settingsRead();

    try {  
        // This block configure the logger with handler and formatter  
        fh = new FileHandler("logs/hudedit_log_" + dateFormat.format(cal.getTime()) + ".log");  
        logger.setLevel(Level.ALL);
        handler.setFormatter(new SimpleFormatter());
        logger.addHandler(handler);
        logger.info("hello world");
        logger.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();  
        fh.setFormatter(formatter);  

        logger.info("Test");  

    } catch (SecurityException e) {  
        e.printStackTrace();  
    } catch (IOException e) {  
        e.printStackTrace();  
    } 

How do I make it so that it takes everything that has been outputted to the console and write it to a file efficiently rather than putting logger.info("Whatever the thing I want to output"); everywhere?

I think you should use Log4j.

http://logging.apache.org/log4j/2.x/

It is very plexible for this routine.

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