Also we would be utilizing the main components of log4j i.e. Logger,Appender and Layout.Lets go step by step.
![]() |
Log4j components |
Implementation:-
Step1:-Creating a new logger:–
Logger logger = Logger.getLogger(“MyLogger”);
MyLogger:-logger name
![]() |
getlogger method |
More usually, one instantiates a static logger globally, based on the name of the class:-
static Logger logger = Logger.getLogger(test.class);
Example:-
/* Getting class name to be printed on */
static Logger log = Logger.getLogger(Log4j_FirstTestCase.class);
Step2:-
Creating the layout object:-
Layout sLayout = new SimpleLayout();
Step3:-
a.Creating the Appender object:-
Appender app = new ConsoleAppender(sLayout);
b.Adding Appender to Logger object
log.addAppender(app);
Step4:-
Calling the available logger levels:-
Priority level = debug < info < warn < error < fatal
![]() |
Logger levels |
![]() |
Adding level to Logger object |
Note:- This priority level is important, as one’s it is applied, only the Log level of that logger and higher than this will be logged. We can set log level of a logger using the Logger.setLevel method.
Example:- If we set the, log.setLevel(Level.WARN), then even if we have code like :- log.Debug(“Debug message”) in our flow, it would not be shown in the output, because as per the priority Debug < Warn.
Code:–
package Log4j_Learning;
import org.apache.log4j.Appender;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
public class Log4j_FirstTestCase {
//Creating the logger object
static Logger log = Logger.getLogger(Log4j_FirstTestCase.class);
public static void main(String[] args) {
//Setting the log level
log.setLevel(Level.WARN);
//Creating the layout object
Layout sLayout = new SimpleLayout();
//Creating the Appender object
Appender app = new ConsoleAppender(sLayout);
//Adding appender to logger
log.addAppender(app);
log.debug("First debug Message");
log.info("First info Message");
log.warn("First Warning Message");
log.error("First Error Message");
log.fatal("First Fatal Message");
}
}
Output:-
Note:- In our case as we used log level =WARN ,thus debug and info message won’t be shown in the output.Also the below output is just for illustration, if You run the above code we will have warn,error and fatal messages.
![]() |
Console output log4j |
Why to avoid above approach:-