Redirecting logging to a file

In this post I will explain how to program the logger to log messages to a file instead of logging to console.

Below is the code

Main code


1  package Logging;
2  
3  import java.io.IOException;
4  import java.util.logging.FileHandler;
5  import java.util.logging.Logger;
6  
7  public class LoggingDemo2 {
8   public static void main(String[] args) throws IOException {
9       Logger logger = Logger.getLogger("logger1");
10      FileHandler fileHandler = null;
11      try {
12          fileHandler = new FileHandler("java.log");
13          logger.addHandler(fileHandler);
14          logger.info("Hello my name is Sumanth");
15          logger.removeHandler(fileHandler);
16      } finally {
17          fileHandler.close();
18      }
19  }
20 }

Explanation

At line 9, we create an instance of Logger class.

At line 12, we create an instance of FileHandler, which is responsible for logging to a file. The file name in this case is “java.log”
The file gets created in project directory.

At line 13, we add this handler to the logger using addHandler method.

At line 14, we log the message.

At line 15, we remove the fileHandler using removeHandler method.

At line 16 we close the FileHandler instance.

Output

2017-06-26T16:10:43
1498473643701
0
logger1
INFO
Logging.LoggingDemo2
main
1
Hello my name is Sumanth

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s