如何使用java.util.logging.Logger在文本文件中写入日志
我有一种情况,我想写我创build的所有日志写入到一个文本文件。
我们使用java.util.logging.Logger API来生成日志。
我试过了
private static Logger logger = Logger.getLogger(className.class.getName()); FileHandler fh; fh = new FileHandler("C:/className.log"); logger.addHandler(fh);
但仍然只有控制台上我的日志….请帮助。 提前致谢
试试这个例子。 它适用于我。
public static void main(String[] args) { Logger logger = Logger.getLogger("MyLog"); FileHandler fh; try { // This block configure the logger with handler and formatter fh = new FileHandler("C:/temp/test/MyLogFile.log"); logger.addHandler(fh); SimpleFormatter formatter = new SimpleFormatter(); fh.setFormatter(formatter); // the following statement is used to log any messages logger.info("My first log"); } catch (SecurityException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } logger.info("Hi How ru?"); }
在MyLogFile.log中生成输出
Apr 2, 2013 9:57:08 AM testing.MyLogger main INFO: My first log Apr 2, 2013 9:57:08 AM testing.MyLogger main INFO: Hi How ru?
编辑:
要删除控制台处理程序,请使用
logger.setUseParentHandlers(false);
因为ConsoleHandler是在所有logging器派生的父logging器上注册的。
首先,你在哪里定义了你的logging器,以及从什么类别的方法试图调用它? 有一个工作的例子,新鲜出炉:
public class LoggingTester { private final Logger logger = Logger.getLogger(LoggingTester.class .getName()); private FileHandler fh = null; public LoggingTester() { //just to make our log file nicer :) SimpleDateFormat format = new SimpleDateFormat("M-d_HHmmss"); try { fh = new FileHandler("C:/temp/test/MyLogFile_" + format.format(Calendar.getInstance().getTime()) + ".log"); } catch (Exception e) { e.printStackTrace(); } fh.setFormatter(new SimpleFormatter()); logger.addHandler(fh); } public void doLogging() { logger.info("info msg"); logger.severe("error message"); logger.fine("fine message"); //won't show because to high level of logging } }
在你的代码中,你忘了定义格式化程序,如果你需要一个简单的程序,你可以像上面提到的那样做,但是还有另一个选项,你可以自己格式化,有一个例子(只需要插入它而不是这行) .setFormatter(new SimpleFormatter())以下代码):
fh.setFormatter(new Formatter() { @Override public String format(LogRecord record) { SimpleDateFormat logTime = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss"); Calendar cal = new GregorianCalendar(); cal.setTimeInMillis(record.getMillis()); return record.getLevel() + logTime.format(cal.getTime()) + " || " + record.getSourceClassName().substring( record.getSourceClassName().lastIndexOf(".")+1, record.getSourceClassName().length()) + "." + record.getSourceMethodName() + "() : " + record.getMessage() + "\n"; } });
或者任何你喜欢的任何其他修改。 希望它有帮助。
一个很好的库,名为log4j for Java 。
这将提供许多function。 通过链接,你会发现你的解决scheme。
int SIZE = "<intialize-here>" int ROTATIONCOUNT = "<intialize-here>" Handler handler = new FileHandler("test.log", SIZE, LOG_ROTATIONCOUNT); logger.addHandler(handler); // for your code.. // you can also set logging levels Logger.getLogger(this.getClass().getName()).log(Level.[...]).addHandler(handler);
import java.io.IOException; import org.apache.log4j.Appender; import org.apache.log4j.FileAppender; import org.apache.log4j.Logger; import org.apache.log4j.SimpleLayout; /** * @author Kiran * */ public class MyLogger { public MyLogger() { } public static void main(String[] args) { Logger logger = Logger.getLogger("MyLog"); Appender fh = null; try { fh = new FileAppender(new SimpleLayout(), "MyLogFile.log"); logger.addAppender(fh); fh.setLayout(new SimpleLayout()); logger.info("My first log"); } catch (SecurityException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } logger.info("Hi How ru?"); } }
也许这是你需要的…
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; /** * LogToFile class * This class is intended to be use with the default logging class of java * It save the log in an XML file and display a friendly message to the user * @author Ibrabel <ibrabel@gmail.com> */ public class LogToFile { protected static final Logger logger=Logger.getLogger("MYLOG"); /** * log Method * enable to log all exceptions to a file and display user message on demand * @param ex * @param level * @param msg */ public static void log(Exception ex, String level, String msg){ FileHandler fh = null; try { fh = new FileHandler("log.xml",true); logger.addHandler(fh); switch (level) { case "severe": logger.log(Level.SEVERE, msg, ex); if(!msg.equals("")) JOptionPane.showMessageDialog(null,msg, "Error", JOptionPane.ERROR_MESSAGE); break; case "warning": logger.log(Level.WARNING, msg, ex); if(!msg.equals("")) JOptionPane.showMessageDialog(null,msg, "Warning", JOptionPane.WARNING_MESSAGE); break; case "info": logger.log(Level.INFO, msg, ex); if(!msg.equals("")) JOptionPane.showMessageDialog(null,msg, "Info", JOptionPane.INFORMATION_MESSAGE); break; case "config": logger.log(Level.CONFIG, msg, ex); break; case "fine": logger.log(Level.FINE, msg, ex); break; case "finer": logger.log(Level.FINER, msg, ex); break; case "finest": logger.log(Level.FINEST, msg, ex); break; default: logger.log(Level.CONFIG, msg, ex); break; } } catch (IOException | SecurityException ex1) { logger.log(Level.SEVERE, null, ex1); } finally{ if(fh!=null)fh.close(); } } public static void main(String[] args) { /* Create simple frame for the example */ JFrame myFrame = new JFrame(); myFrame.setTitle("LogToFileExample"); myFrame.setSize(300, 100); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.setLocationRelativeTo(null); JPanel pan = new JPanel(); JButton severe = new JButton("severe"); pan.add(severe); JButton warning = new JButton("warning"); pan.add(warning); JButton info = new JButton("info"); pan.add(info); /* Create an exception on click to use the LogToFile class */ severe.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent ae) { int j = 20, i = 0; try { System.out.println(j/i); } catch (ArithmeticException ex) { log(ex,"severe","You can't divide anything by zero"); } } }); warning.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent ae) { int j = 20, i = 0; try { System.out.println(j/i); } catch (ArithmeticException ex) { log(ex,"warning","You can't divide anything by zero"); } } }); info.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent ae) { int j = 20, i = 0; try { System.out.println(j/i); } catch (ArithmeticException ex) { log(ex,"info","You can't divide anything by zero"); } } }); /* Add the JPanel to the JFrame and set the JFrame visible */ myFrame.setContentPane(pan); myFrame.setVisible(true); } }
日志文件的位置可以通过logging.properties文件来控制。 它可以作为JVM参数ex传递: java -Djava.util.logging.config.file=/scratch/user/config/logging.properties
详细信息: https : //docs.oracle.com/cd/E23549_01/doc.1111/e14568/handler.htm
configuration文件处理程序
要将日志发送到文件,请将FileHandler添加到logging.properties文件中的处理程序属性中。 这将启用全局文件logging。
handlers= java.util.logging.FileHandler
通过设置以下属性来configuration处理程序:
java.util.logging.FileHandler.pattern=<home directory>/logs/oaam.log java.util.logging.FileHandler.limit=50000 java.util.logging.FileHandler.count=1 java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter
java.util.logging.FileHandler.pattern指定输出文件的位置和模式。 默认设置是您的主目录。
java.util.logging.FileHandler.limit以字节为单位指定logging器写入任何一个文件的最大数量。
java.util.logging.FileHandler.count指定要循环的输出文件数量。
java.util.logging.FileHandler.formatter指定文件处理程序类用于格式化日志消息的java.util.logging格式器类。 SimpleFormatter写简短的“人类可读的”日志logging摘要。
要指示java使用此configuration文件而不是$ JDK_HOME / jre / lib / logging.properties:
java -Djava.util.logging.config.file=/scratch/user/config/logging.properties
这里是我接受答案的日志类:
import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.*; public class ErrorLogger { private Logger logger; public ErrorLogger() { logger = Logger.getAnonymousLogger(); configure(); } private void configure() { try { String logsDirectoryFolder = "logs"; Files.createDirectories(Paths.get(logsDirectoryFolder)); FileHandler fileHandler = new FileHandler(logsDirectoryFolder + File.separator + getCurrentTimeString() + ".log"); logger.addHandler(fileHandler); SimpleFormatter formatter = new SimpleFormatter(); fileHandler.setFormatter(formatter); } catch (IOException exception) { exception.printStackTrace(); } addCloseHandlersShutdownHook(); } private void addCloseHandlersShutdownHook() { Runtime.getRuntime().addShutdownHook(new Thread(() -> { // Close all handlers to get rid of empty .LCK files for (Handler handler : logger.getHandlers()) { handler.close(); } })); } private String getCurrentTimeString() { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); return dateFormat.format(new Date()); } public void log(Exception exception) { logger.log(Level.SEVERE, "", exception); } }