- Logging is very important part of programming. Logging helps programmer to understand process flow and identify the problems where actually occurred.
- Log4J will be configured externally using properties file. We can print the logging statements in the console or we can push them in to a log file based on the requirement.
- org.apache.log4j class will provide required classes to implement logging
- We need to add Log4J dependency in our project.
- Create instance of logger by using Logger.getLogger(Log4JExample.class);
- Lets see how to create log4j.properties file in eclipse
1. Create a maven project and add Log4J dependency:
2. Create log4j.properties file
- log4j.rootLogger=INFO, console
- log4j.appender.console=org.apache.log4j.ConsoleAppender
- log4j.appender.console.layout=org.apache.log4j.PatternLayout
- log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS zzz}
3.Create java example program to read log4j.properties file
- import org.apache.log4j.BasicConfigurator;
- import org.apache.log4j.Logger;
- public class Log4JExample {
- static Logger logger = Logger.getLogger(Log4JExample.class);
- public static void main(String[] args)
- {
- BasicConfigurator.configure();
- logger.info("main method start!!");
- System.out.println("hi");
- logger.info("log4j properties configuration example");
- logger.info("main method end!!");
- }
- }
Output:
- 2018-02-08 23:09:10.747 IST0 [main] INFO Log4JExample - main method start!!
- hi
- 2018-02-08 23:09:10.752 IST5 [main] INFO Log4JExample - log4j properties configuration example
- 2018-02-08 23:09:10.753 IST6 [main] INFO Log4JExample - main method end!!
No comments