How to Write Logs in Text File When Using Java.Util.Logging.Logger

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

Try this sample. It 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 r u?");

}

Produces the output at 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 r u?

Edit:

To remove the console handler, use

logger.setUseParentHandlers(false);

since the ConsoleHandler is registered with the parent logger from which all the loggers derive.

Problem getting Java to write logs to file

From what I could tell your logging was outputting to a file and seemed to be working.

However, I noticed the logs were difficult to parse due to the format being xml-record based, so I used a SimpleFormatter in my solution to read the logs at a line level.

Solution:

 public static void main(String[] args) {

Logger logger = Logger.getLogger("");
FileHandler fileHandler;

try {
fileHandler = new FileHandler("Test.logon.log.txt");
logger.addHandler(fileHandler);

SimpleFormatter formatter = new SimpleFormatter();
fileHandler.setFormatter(formatter);
logger.info("0.0 - My first log");
logger.info("1.0 - Test log");

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

I hope this helps.

How to log a message from java.util.logging.Logger Logging and then print it to a text file?

I would do this:

public ControllerException(final String message, int errorcode) {
super(message);
this.errorcode=errorcode;

Logger logger = Logger.getLogger(ControllerException.class.getName());

logger.setFilter(new Filter() {
@Override
public boolean isLoggable(LogRecord record) {
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd',' yyyy HH:mm:ss a");
String fileName = "error.log";

try {
PrintWriter outputStream = new PrintWriter(fileName);
outputStream.println("Time: " + sdf.format(new Date(record.getMillis())));
outputStream.println("Reason: " + message);
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}

return true;
}
});

logger.info(message);
}

This way you get the exact date of the log record.

Why java.util.logging is not writing logs to file?

Add Handler

     logger = Logger.getLogger(MyClass.class.getName());
logger.addHandler(handler);


Related Topics



Leave a reply



Submit