java - I am trying to log text from the console to a text file, and the text file isn't being created -
here code, wondering why isn't logging anything. when type console says:
hello
apr 08, 2013 10:13:47 pm java.util.logging.logmanager$rootlogger log
info: hello
however, nothing being logged files.
import java.io.ioexception; import java.util.scanner; import java.util.logging.filehandler; import java.util.logging.level; import java.util.logging.logger; import java.util.logging.simpleformatter; public class main { public static void main(string[] args) throws ioexception{ while (1 == 1) { string text; scanner in = new scanner(system.in); text = in.nextline(); filehandler filetxt; simpleformatter formattertxt; logger logger = logger.getlogger(""); logger.setlevel(level.info); filetxt = new filehandler("../loggedtext.txt"); formattertxt = new simpleformatter(); filetxt.setformatter(formattertxt); logger.addhandler(filetxt); logger.info(text); } } }
your loop never terminates means jvm never performs proper shutdown. filehandler closed , synched if logging shutdown hook executes normally. possible data written never synched filesystem.
let's create corrected example can terminate normally:
public class main { private static final logger logger = logger.getlogger(""); //prevent g.c. public static void main(string[] args) throws ioexception { logger.setlevel(level.info); filehandler filetxt = new filehandler("../loggedtext.txt"); filetxt.setformatter(new simpleformatter()); logger.addhandler(filetxt); system.out.println("root.level " + logger.getlevel()); system.out.println("filehandler.level " + filetxt.getlevel()); scanner in = new scanner(system.in); string text; while (true) { system.out.print("enter text: "); text = in.nextline(); if (text != null && !text.isempty() && !"quit".equalsignorecase(text)) { logger.info(text); } else { system.out.println("done!"); break; } } } }
will output following console:
root.level info filehandler.level enter text: hello nov 22, 2016 10:39:19 java.util.logging.logmanager$rootlogger log info: hello enter text: quit done!
on filesystem loggedtext.txt
containing:
nov 22, 2016 10:39:19 java.util.logging.logmanager$rootlogger log info: hello
if can't terminate need explicitly call filehandler.close()
on handlers create.
note: logged class name , method name incorrect known jdk-8152389.
Comments
Post a Comment