How to write logs to text file when using java.util.logging.Logger

I have a situation in which I want to write all the logs I created to a text file.

We use the java.util.logging.Logger API to generate logs.

I did my best:

private static Logger logger = Logger.getLogger(className.class.getName()); FileHandler fh; fh = new FileHandler("C:/className.log"); logger.addHandler(fh); 

But still receive my logs only on the console ....

+124
java logging
Apr 02 '13 at 7:41
source share
9 answers

Try this sample. This works for me.

 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?"); } 

Produces output in 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? 

Edit:

To remove the console handler, use

 logger.setUseParentHandlers(false); 

because ConsoleHandler is registered in the parent log, from which all registrars exit.

+215
Apr 02 '13 at 7:46
source share

First, where did you define your registrar and what class / method is trying to call it? There is a working example freshly baked:

 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 } } 

In your code, you forgot to define the formatter, if you need a simple one, you can do it, as I mentioned above, but there is another option, you can format it yourself, there is an example (just insert it instead of this line fh.setFormatter (new SimpleFormatter ()) following code):

 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"; } }); 

Or any other modification, anything. Hope this helps.

+15
Jun 23 '14 at 16:58
source share

The location of the log file can be controlled through the logging.properties file. And it can be passed as a JVM parameter, for example: java -Djava.util.logging.config.file=/scratch/user/config/logging.properties

Details: https://docs.oracle.com/cd/E23549_01/doc.1111/e14568/handler.htm

File Handler Setup

To send logs to a file, add FileHandler to the handler property in the logging.properties file. This will enable file logging globally.

handlers= java.util.logging.FileHandler Configure the handler by setting the following properties:

 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 indicates the location and pattern of the output file. The default value is your home directory.

java.util.logging.FileHandler.limit indicates in bytes the maximum amount that the registrar writes to any file.

java.util.logging.FileHandler.count indicates how many output files to iterate over.

java.util.logging.FileHandler.formatter specifies the java.util.logging formatter class, which the file handler class uses to format log messages. SimpleFormatter records short โ€œreadableโ€ summaries of journal entries.

To tell java to use this configuration file instead of $ JDK_HOME / jre / lib / logging.properties:

 java -Djava.util.logging.config.file=/scratch/user/config/logging.properties 
+6
Jan 31 '17 at 5:34 on
source share

A good library available with the name log4j for Java .
This will provide numerous functions. Follow the link and you will find your solution.

+5
Apr 02 '13 at 7:47 on
source share

Maybe this is what you need ...

 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); } } 
+5
Apr 10 '14 at 9:35
source share
 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?"); } } 
+4
Oct 01 '13 at 6:42 on
source share
 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); 
+3
Apr 02 '13 at 7:49
source share

I hope people find this useful

 public static void writeLog(String info) { String filename = "activity.log"; String FILENAME = "C:\\testing\\" + filename; BufferedWriter bw = null; FileWriter fw = null; try { fw = new FileWriter(FILENAME, true); bw = new BufferedWriter(fw); bw.write(info); bw.write("\n"); } catch (IOException e) { e.printStackTrace(); } finally { try { if (bw != null) bw.close(); if (fw != null) fw.close(); } catch (IOException ex) { ex.printStackTrace(); } } } 
+1
Nov 20 '18 at 22:51
source share

Here is my logging class based on accepted answer :

 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); } } 
0
Jun 18 '17 at 13:33 on
source share



All Articles