Also we would be utilizing the main components of log4j i.e. Logger,Appender and Layout.Lets go step by step.
Step1:-Creating a new logger:–
Logger logger = Logger.getLogger(“MyLogger”);
More usually, one instantiates a static logger globally, based on the name of the class:-
static Logger logger = Logger.getLogger(test.class);
Creating the layout object:-
Layout sLayout = new SimpleLayout();
a.Creating the Appender object:-
Appender app = new ConsoleAppender(sLayout);
b.Adding Appender to Logger object
Calling the available logger levels:-
Priority level = debug < info < warn < error < fatal
|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.
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:-