Nearby lessons

35 of 35

Spring - Log4j Integration

📌 What You Will Learn
  • Understand Spring - Log4j Integration
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Spring - Log4j Integration step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

Log4j

Log4J is a reliable, fast and flexible framework written in JAVA to perform logging in Java applications and it is provided by Apache Software Foundations.

Log4j Features

Log4j is able to allow more than one thread at a time with out providing data inconsistency ,so that, Log4j is thread-safe. Log4j will not slow down the application execution, it will be optimized to improve application performance. Log4j is providing environment to send logging messages to more than one output appenders . Log4j supports internationalization. Log4j is providing services for both predefined and user defined facilities, it able to provide some customizations also. Log4j allows to set logging behaviours at runtime through the configuration file. Log4j is providing very good environment to traace Exceptions from its root. Log4j uses multiple levels like ALL, TRACE, DEBUG, INFO, WARN, ERROR and FATAL to generate messages. Log4j allows to change the format of log output by extending Layout class. Log4j is using appenders to generate log messages.

Log4j Arch contains mainly the following Objects

  • Logger
  • Appender
  • Layout
  • Level
  • LogManager
  • Filter
  • ObjectRender

Logger

This Object is responsibile to get logging messages from Java applications

Appender

The main intention of Appender object is to get logging messages from Logger object and publishing that logging messages to the preffered destinations. Each and Every Appender Object must have atleast one Destination object inorder to send logging messages.

EX: ConsoleAppender is able to store logging messages on Console.

Layout

The main intention of Layout object is to format logging messages in different styles.Layout Object is used by Appender object just before publishing Logging Messages.

Level

The main intention of Level object is to define granualarity and priority of any Logging information. Each and every Logging information must be with a particular Logging Level.

Log4j API has provided the following Levels to the Logging messages.

  • ALL
  • TRACE
  • DEBUG
  • ENFO
  • WRAN
  • ERROR
  • FATAL
  • OFF

Log4j is giving priorities for the logging messages in the following order. ALL >TRACE > DEBUGG > INFO > WARN > ERROR > FATAL>OFF

LogManager

LogManager is the central component , it able to manage Log4j framework, it will read all the initial configuration details from the configuration file and stored the Logger objects in namespace hierarchy with a particular reference name for futer reference. If our application access any Logger object on the basis of the reference name then LogManager will return the existed Logger object otherwise it will create new Logger object and return to the application.

Filter

The main intention of Filter object is used to analyze logging information and takes the decision whther the messages must be logged or not. An Appender object may have no of Filter objects, they must approve our logging message before publishing logging messages in destination.

ObjectRender

This Object will be used by Layout object in order to get string representation of the several objects which are passed through Log4j framework.

Log4j Internal Flow

  • If we create Logger object in Java application then a request will be send to Log4j Software about to create Logger object.
  • Log4j Software will search for log4j.properties/log4j.xml file in classpath, if it is existed then

Log4j Software will load and parse log4j configuration file then Log4j software will create Logger object.

  • After creating Logger object, Log4j Software will return Logger object to Java Application.
  • If we access any logger method from Logger reference then Java application will send logging responsibility to Log4j software.
  • Log4j Software will activate Appender object inorder to perform logging.
  • Appender will recognize all the filters which are associated then Appender will execute all the filters in sequence, where filters will filters the logging messages to persist or display.
  • Appender will activate Layout object , it will apply the layout styles on the logging messages.
  • After Styling Logging messages, Appender will activate Object Renderer to recognize the destination.
  • Sending Logging messages to the respective Destination.

Log4j Configuration File

Log4j Configuration File includes all Log4j configuration details like rootLogger, Layout configurations, Appenders configuration,.

In Log4j , we are able to use the following two types of configuration files.

  • log4j.properties
  • log4j.xml

IN both the configuratin files, we have to use the following configurations at basic java applications.

  • Declare rootLogger and initialize rootLogger
  • Declare appender
  • Declare Layout and its conversionPattern.

EX: log4j.properties

 log4j.rootLogger =TRACE, 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 } : This is

%m%n

 Where "log4j.rootLogger" property will take Logging LEVEL and appender name,  where Log4j framework will display all the messages which are same as the specified Log

level and lower than the specified Log level.  Where appender name is a name which is referring a particular Appender.

EX: log4j.rootLogger = TRACE, CONSOLE

Where "log4j.appender.CONSOLE" property will take a particular Appender like ConsoleAppender, FileAppender,...

EX: log4j.appender.CONSOLE = org.apache.log4j.ConsoleAppender

Where "log4j.appender.CONSOLE.layout" property will configure Layout configfuration.

EX: log4j.appender.CONSOLE.layout = org.apache.log4j.PatternLayout

Where PattrenLayout needs a property like conversionPattern to take a particular pattern to display messages.

EX: "log4j.appender.CONSOLE.layout.conversionPattern = %m%n

Note: Where %m%n in the sense, %m is to display message and %n is to bring cursor to next line.

log4j.xml Configuration — log4j.xml

In XML confioguration we have to use the following configuration.

  • Appender configuration.
  • Layout Configuration
  • Root Logger COnfiguration

To provide XML configuration then we have to use the following xml tags in log4j.xml file.

Example14
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
4<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
5debug="false">
6 
7<appender name="console" class="org.apache.log4j.ConsoleAppender">
8<layout class="org.apache.log4j.PatternLayout">
9 <param name="ConversionPattern" value="%d{DD/MM/YYYY HH:mm:SS} %-5p %c{1} - %m%n" />
10</layout>
11</appender>
12 
13<root>
14<priority value="ERROR" />
15<appender-ref ref="console" />
16</root>
17 
18</log4j:configuration>
19

log4j.xml Configuration

 Where <log4j:configuration> isa a root tag, it able to take log4j configuration details.  Where <appender> tag is able to configure Appender class with a logical name.  Where "name" attribute in <appender> tag will take logical name to the appender.  Where "class" attribute in <appender> tag is able to take fully qualified name of the

Appender class, that is, "org.apache.log4j.ConsoleAppender"  Where <layout> tag can be used to configure Layout class.  Where "class" attribute in <layout> tag will take fully qualified name of Layout class, that is,

"org.apache.log4j.PatternLayout".  Where <param> tag in <layout> tag will take layout parameter .  Where "name" attribute will take parameter name, tyhat is , "ConversionPattern".  Where "value" attribute will take value of the parameter , that is, %d{DD/MM/YYYY

HH:mm:SS} %-5p %c{1} - %m%n  Where <root> tag will provide rootLogger configuration.  Where <priority> tag tag will take logger level with "value" attribute.  Where <appender-ref> tag will take logical name of the appender with "ref" attribute.

Steps to Use Log4j in Java Application

  • Download log4j-1.2.17.zip from "https://logging.apache.org/log4j/1.2/download.html"
  • Create Java project in Eclipse IDE and add log4j1.2.17.jar file in build path
  • Create log4j configuration file[log4j.properties or log4j.xml].
  • Create Java class.
  • Run Java project [Suggestible in Debug mode].

Example:

log4j.properties — Log4jTest.java

 log4j.rootLogger =FATAL, 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 } : This is

%m%n

Example17
JCode Cell
1 
2package log4japp1;
3 
4import org.apache.log4j.LogManager;
5import org.apache.log4j.Logger;
6 
7public class Log4jTest {
8 
9public static void main(String[] args) {
10 Logger logger = LogManager.getLogger(Log4jTest.class);
11logger.trace("trace Message");
12logger.debug("debug Message");
13logger.info("info Message");
14logger.warn("warn Message");
15logger.error("Error Message");
16logger.fatal("fatal Message");
17 
18}
19}
20

log4j.properties — log4j.xml

Note: If we want to use XML configuration then we have to use the following XML file

Example18
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
4<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
5debug="false">
6 
7<appender name="console" class="org.apache.log4j.ConsoleAppender">
8<layout class="org.apache.log4j.PatternLayout">
9 <param name="ConversionPattern" value="%d{DD/MM/YYYY HH:mm:SS} %-5p %c{1} - %m%n" />
10</layout>
11</appender>
12 
13<root>
14<priority value="ERROR" />
15<appender-ref ref="console" />
16</root>
17 
18</log4j:configuration>
19

Appenders

Appender is an object, it can be used to get logging messages from Logger object and publishing that logging messages to the preffered destinations. Each and Every Appender Object must have atleast one Destination object inorder to send logging messages.

Log4j has provided the following appenders inorder to publish logging messages.

  • ConsoleAppender
  • FileAppender
  • JDBCAppender
  • JMSAppender
  • SocketAppender
  • SMTPAppender
  • AsyncAppender
  • AppenderSkeleton
  • DailyRollingFileAppender
  • ExternallyRolledFileAppender
  • LF5Appender
  • NTEventLogAppender
  • NullAppender
  • RollingFileAppender
  • SocketHubAppender
  • SyslogAppender
  • TelnetAppender
  • WriterAppender

If we want to manage all logging messages in a File then we have to use FileAppenders.

There are Four types of File Appenders.

  • FileAppender
  • RollingFileAppender
  • DailyRollingFileAppender
  • ExternallyRolledFileAppender

FileAppender

If we want to use FileAppender in Java applications then we have to use the following properties in log4j.properties file.

  • log4j.rootLogger
  • log4j.appender.Ref_Name
  • log4j.appender.Ref_Name.File : It will name and location of the file to manage logging

messages.

  • log4j.appender.Ref_Name.layout
  • log4j.appender.Ref_Name.layout.ConversionProperty

EX:

log4j.properties — Log4jTest.java

 log4j.rootLogger =ALL, FILE  log4j.appender.FILE = org.apache.log4j.FileAppender  log4j.appender.FILE.File=./logging/logs.log  log4j.appender.FILE.layout = org.apache.log4j.PatternLayout  log4j.appender.FILE.layout.conversionPattern = %d{yyyy-mm-dd hh:mm:ss } : This is

%m%n

Example21
JCode Cell
1 
2package log4japp1;
3 
4import org.apache.log4j.LogManager;
5import org.apache.log4j.Logger;
6 
7public class Log4jTest {
8 
9public static void main(String[] args) {
10 
11Logger logger = LogManager.getLogger(Log4jTest.class);
12logger.trace("trace Message");
13logger.debug("debug Message");
14logger.info("info Message");
15logger.warn("warn Message");
16logger.error("Error Message");
17logger.fatal("fatal Message");
18 
19}
20}
21

log4j.properties

If we want to use both ConsoleAppender and FileAppender in Java Applications then we have to define two Ref_Names at 'log4j.rootLogger' property.

EX:

log4j.properties

log4j.rootLogger =ALL, CONSOLE, FILE

#ConsoleAppender Configuration

 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 } %-c %p

: This is %m%n

#FileAppender Configuration

 log4j.appender.FILE = org.apache.log4j.FileAppender  log4j.appender.FILE.File=./logging/logs.log  log4j.appender.FILE.layout = org.apache.log4j.PatternLayout

 log4j.appender.FILE.layout.conversionPattern = %d{yyyy-mm-dd hh:mm:ss } %-c %p — Log4jTest.java

This is %m%n

Example24
JCode Cell
1 
2package log4japp1;
3 
4import org.apache.log4j.LogManager;
5import org.apache.log4j.Logger;
6 
7public class Log4jTest {
8 
9public static void main(String[] args) {
10 
11Logger logger = LogManager.getLogger(Log4jTest.class);
12logger.trace("trace Message");
13logger.debug("debug Message");
14logger.info("info Message");
15logger.warn("warn Message");
16logger.error("Error Message");
17logger.fatal("fatal Message");
18 
19}
20}
21

RollingFileAppender

The main intention of RollingFileAppender is to manage logging messages to the other new files when the present log file is getting exceded as per the file size limit.

If we want to use RollingFileAppender in log4j applications then we have to use "org.apache.log4j.RollingFileAppender" class and we have to use all the FileAppender properties and the following extra properties.

  • log4j.appender.Ref_Name.MaxFileSize : It will take max File size in the form of KB
  • log4j.appender.Ref_Name.MaxBackupIndex= It able to create maximum backup files.

EX:

log4j.properties

log4j.rootLogger =ALL, FILE

#FileAppender Configuration

 log4j.appender.FILE = org.apache.log4j.RollingFileAppender  log4j.appender.FILE.file= e:/loggers/logs.txt  log4j.appender.FILE.MaxFileSize= 2kb  log4j.appender.FILE.MaxBackupIndex= 3  log4j.appender.FILE.layout = org.apache.log4j.PatternLayout

 log4j.appender.FILE.layout.conversionPattern = %d{yyyy-mm-dd hh:mm:ss } %-c %p — Log4jTest.java

This is %m%n

Example27
JCode Cell
1 
2package log4japp1;
3 
4import org.apache.log4j.LogManager;
5import org.apache.log4j.Logger;
6 
7public class Log4jTest {
8static Logger logger = LogManager.getLogger(Log4jTest.class);
9public static void main(String[] args) {
10 
11logger.trace("trace Message");
12logger.debug("debug Message");
13logger.info("info Message");
14logger.warn("warn Message");
15logger.error("Error Message");
16logger.fatal("fatal Message");
17 
18}
19}
20

DailyRollingFileAppender

The main intention of DailyRollingFileAppender is to roll files in FileAppender on daily basis.

If we want to use DailyRollingFileAppender in log4j applications then we have to use "org.apache.log4j.DailyRollingFileAppender" and we have to use "datePattern" property in properties file. Note: If we are using DailyRollingFileAppender in our application then it is not required to use "maxFileSize" and "maxBackupIndex" properties in log4j.properties file.

Note: The default pattern for datePattern property is '.' '.' yyyy-MM-dd , it will roll over every day midnight

For "datePattern" property we are able to use the following values.

  • '.' yyyy-MM : It will roll over at the end of each month and at the beginning of the next month.
  • '.' yyyy-MM-dd : It will roll over at midnight each day.
  • '.' yyyy-MM-dd-a :It will roll over at midday and midnight of each day.
  • '.' yyyy-MM-dd-HH : It will roll over at the top of every hour.
  • '.' yyyy-MM-dd-HH-mm : It will roll over every minute.
  • '.' yyyy-ww : It will roll over on the first day of each week depending upon the locale.

Example:

log4j.properties

log4j.rootLogger =ALL, FILE

#FileAppender Configuration

 log4j.appender.FILE = org.apache.log4j.DailyRollingFileAppender  log4j.appender.FILE.file= e:/loggers/logs.txt  log4j.appender.FILE.DatePattern='.' yyyy-MM-dd-HH-mm  #log4j.appender.FILE.MaxFileSize= 2kb  #log4j.appender.FILE.MaxBackupIndex= 3  log4j.appender.FILE.layout = org.apache.log4j.PatternLayout

 log4j.appender.FILE.layout.conversionPattern = %d{yyyy-mm-dd hh:mm:ss } %-c %p — Log4jTest.java

This is %m%n

Example30
JCode Cell
1 
2package log4japp1;
3 
4import org.apache.log4j.LogManager;
5import org.apache.log4j.Logger;
6 
7public class Log4jTest {
8static Logger logger = LogManager.getLogger(Log4jTest.class);
9public static void main(String[] args) {
10 
11 
12logger.trace("trace Message");
13logger.debug("debug Message");
14logger.info("info Message");
15logger.warn("warn Message");
16logger.error("Error Message");
17logger.fatal("fatal Message");
18 
19}
20}
21

ExternallyRolledFileAppender

This appender listens on a socket on the port specified by the Port property for a "RollOver" message. When such a message is received, the underlying log file is rolled over and an acknowledgment message is sent back to the process initiating the roll over.

Note: ExternallyRolledFileAppender is required Socket Programming and it is deprecated Layouts

Layouts

The main intention of Layout is to define a partidular Structer for the logging messages.

There are four types of Layouts existed in Log4j.

  • SimpleLayout
  • PatternLayout
  • HTMLLayout
  • XMLLayout

Simple Layout

SimpleLayout is able to prepare logging messages with "LEVEL - Log_Message" . Log4j has provided a predefiend class to represent Simple Layout,that is, org.apache.log4j.SimpleLayout

EX:

log4j.properties — Test.java

 log4j.rootLogger = ALL, FILE  log4j.appender.FILE = org.apache.log4j.FileAppender  log4j.appender.FILE.file = E:/loggers/logs.log  log4j.appender.FILE.layout = org.apache.log4j.SimpleLayout

Example34
JCode Cell
1 
2package com.durgasoft.log4j;
3import org.apache.log4j.LogManager;
4import org.apache.log4j.Logger;
5 
6public class Log4jTest {
7static Logger logger = LogManager.getLogger(Log4jTest.class);
8public static void main(String[] args) {
9 logger.trace("Trace Message");
10 logger.debug("Debug Message");
11logger.info("Info Message");
12logger.warn("Warn Message");
13logger.error("Error Message");
14logger.fatal("Fatal Message");
15 
16}
17 
18}
19

OP

TRACE - Trace Message DEBUG - Debug Message INFO - Info Message WARN - Warn Message ERROR - Error Message FATAL - Fatal Message

Pattern Layout

It able to prepare logging messages w.r.t the provided pattern. To represent Pattern Layout, Log4j has provided a predefined class in the form of "org.apache.log4j.PatternLayout".

To define pattern for the logging messages, we must use "ConversionPattern" property from PatternLayout class.

EX:

log4j.properties

 log4j.rootLogger = ALL, FILE  log4j.appender.FILE = org.apache.log4j.FileAppender  log4j.appender.FILE.file = E:/loggers/logs.log  log4j.appender.FILE.layout = org.apache.log4j.PatternLayout

 log4j.appender.FILE.layout.conversionPattern = %d{dd/MM/YYYY HH:mm:SS} %-c %p — Log4jTest.java

This Is %m%n

Example38
JCode Cell
1 
2package com.durgasoft.log4j;
3 
4import org.apache.log4j.LogManager;
5import org.apache.log4j.Logger;
6 
7public class Log4jTest {
8static Logger logger = LogManager.getLogger(Log4jTest.class);
9public static void main(String[] args) {
10 logger.trace("Trace Message");
11logger.debug("Debug Message");
12logger.info("Info Message");
13logger.warn("Warn Message");
14logger.error("Error Message");
15logger.fatal("Fatal Message");
16 
17}
18 
19}
20

OP

 22/08/2018 18:50:885 com.durgasoft.log4j.Log4jTest TRACE : This Is Trace Message  22/08/2018 18:50:886 com.durgasoft.log4j.Log4jTest DEBUG : This Is Debug Message  22/08/2018 18:50:886 com.durgasoft.log4j.Log4jTest INFO : This Is Info Message  22/08/2018 18:50:886 com.durgasoft.log4j.Log4jTest WARN : This Is Warn Message  22/08/2018 18:50:886 com.durgasoft.log4j.Log4jTest ERROR : This Is Error Message  22/08/2018 18:50:886 com.durgasoft.log4j.Log4jTest FATAL : This Is Fatal Message

Note: We will use these patterns in general in PatternLayout for ConversionPattern property.

%d ----> Date %c ----> Class to which we are providing Logging %P ----> Logging Level %L ----> Line NUmber %m ----> Logging Message %n ----> New Line Character

HTML Layout

It able to provide all logging messages in the form of Html file. To represent this Layout Log4j has provided a predefined class in the form of "org.apache.log4j.HTMLLayout"

EX:

log4j.properties — Log4jTest.java

 log4j.rootLogger = ALL, FILE  log4j.appender.FILE = org.apache.log4j.FileAppender  log4j.appender.FILE.file = E:/loggers/logs.html  log4j.appender.FILE.layout = org.apache.log4j.HTMLLayout

Example41
JCode Cell
1 
2package com.durgasoft.log4j;
3 
4import org.apache.log4j.LogManager;
5import org.apache.log4j.Logger;
6 
7public class Log4jTest {
8static Logger logger = LogManager.getLogger(Log4jTest.class);
9public static void main(String[] args) {
10 logger.trace("Trace Message");
11logger.debug("Debug Message");
12logger.info("Info Message");
13logger.warn("Warn Message");
14logger.error("Error Message");
15logger.fatal("Fatal Message");
16}
17}
18

XML Layout

It able to provide logging messages in the form of XML document. To rperepsent XMLLayout, Log4j has provided a predefined class in the form of "org.apache.log4j.xml.XMLLayout"

EX:

log4j.properties — Log4jTest.java

log4j.rootLogger = ALL, FILE log4j.appender.FILE = org.apache.log4j.FileAppender log4j.appender.FILE.file = E:/loggers/logs.xml log4j.appender.FILE.layout = org.apache.log4j.xml.XMLLayout

Example43
JCode Cell
1 
2package com.durgasoft.log4j;
3import org.apache.log4j.LogManager;
4import org.apache.log4j.Logger;
5 
6public class Log4jTest {
7static Logger logger = LogManager.getLogger(Log4jTest.class);
8public static void main(String[] args) {
9 logger.trace("Trace Message");
10 logger.debug("Debug Message");
11logger.info("Info Message");
12logger.warn("Warn Message");
13logger.error("Error Message");
14logger.fatal("Fatal Message");
15}
16}
17

log4j.properties — Test.java

 log4j.rootLogger = ALL, FILE  log4j.appender.FILE = org.apache.log4j.FileAppender  log4j.appender.FILE.file = E:/loggers/logs.txt  log4j.appender.FILE.append = false  log4j.appender.FILE.layout = org.apache.log4j.PatternLayout  log4j.appender.FILE.layout.conversionPattern = %d{dd/MM/YYYY HH:mm:SS} %-c %p

%L : %m%n

Example44
JCode Cell
1 
2package com.durgasoft.jdbc;
3 
4import java.sql.Connection;
5import java.sql.DriverManager;
6import java.sql.ResultSet;
7import java.sql.Statement;
8 
9import org.apache.log4j.LogManager;
10import org.apache.log4j.Logger;
11 
12public class Test {
13//static Logger logger = LogManager.getLogger(Test.class);
14static Logger logger = Logger.getLogger(Test.class);
15public static void main(String[] args) {
16logger.info("Application Starting Point");
17Connection con = null;
18Statement st = null;
19ResultSet rs = null;
20try {
21 Class.forName("oracle.jdbc.OracleDriver");
22 logger.info("Driver Loaded");
23 con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "durga");
24 if(con == null) {
25 logger.warn("Connection Not Created ");
26 }else {
27 logger.info("Connection Established :"+con);
28 }
29 st = con.createStatement();
30 if(st == null) {
31 logger.warn("Statement is not created");
32 }else {
33 logger.info("Statement is Created :"+st);
34 }
35 String query = "select *emp1";
36 rs = st.executeQuery(query);
37 if(rs == null) {
38 logger.warn("ResultSet is not Created with '"+query+"'");
39 }else {
40 logger.info("ResultSet Object is Created :"+rs);
41 }
42 System.out.println("ENO\tENAME\tESAL\tEADDR");
43 System.out.println("------------------------------");
44 while(rs.next()) {
45 System.out.print(rs.getInt("ENO")+"\t");
46 System.out.print(rs.getString("ENAME")+"\t");
47 System.out.print(rs.getFloat("ESAL")+"\t");
48 System.out.println(rs.getString("EADDR"));
49 }
50} catch (Exception e) {
51 e.printStackTrace();
52 logger.error("Exception :"+e.toString());
53}finally {
54 try {
55 
56 rs.close();
57 st.close();
58 con.close();
59 logger.info("Closing all Resources");
60 } catch (Exception e) {
61 e.printStackTrace();
62 }
63}
64logger.info("End of main(");
65}
66}
67

Log4j in Web Applications — loginform.html

  • Keep Log4j1.2.7.jar in web application lib folder.
  • Prepare Configuration File under src folder / under classes folder.
  • It is suggestible to use FileAppenders.
  • In Servlets generate Loggers.

Example:

Example45
JCode Cell
1 
2<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
3<html>
4<head>
5<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
6<title>Insert title here</title>
7</head>
8<body>
9<h2>Durga Software Solutions</h2>
10<h3>User Login Page</h3>
11<form method="POST" action="./login">
12<table>
13<tr>
14<td>User Name</td>
15<td><input type="text" name="uname"/></td>
16</tr>
17<tr>
18<td>Password</td>
19<td><input type="password" name="upwd"/></td>
20</tr>
21<tr>
22<td><input type="submit" value="Login"/></td>
23</tr>
24</table>
25</form>
26</body>
27</html>
28

Log4j in Web Applications — success.html

Example46
JCode Cell
1 
2<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
3<html>
4<head>
5<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
6<title>Insert title here</title>
7</head>
8<body>
9<h2>Durga Software Solutions</h2>
10<h3>User Login Status</h3>
11<h2>
12Login Success
13</h2>
14<h3>
15<a href="./loginform.html">|Login Page|</a>
16</h3>
17</body>
18</html>
19

Log4j in Web Applications — failure.html

Example47
JCode Cell
1 
2<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
3<html>
4<head>
5<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
6<title>Insert title here</title>
7</head>
8<body>
9<h2>Durga Software Solutions</h2>
10<h3>User Login Status</h3>
11<h2>
12Login Failure
13</h2>
14<h3>
15<a href="./loginform.html">|Login Page|</a>
16</h3>
17</body>
18</html>
19

Log4j in Web Applications — web.xml

Example48
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
4<display-name>app4</display-name>
5<welcome-file-list>
6<welcome-file>index.html</welcome-file>
7<welcome-file>index.htm</welcome-file>
8<welcome-file>index.jsp</welcome-file>
9<welcome-file>default.html</welcome-file>
10<welcome-file>default.htm</welcome-file>
11<welcome-file>default.jsp</welcome-file>
12</welcome-file-list>
13<servlet>
14<description></description>
15<display-name>LoginServlet</display-name>
16<servlet-name>LoginServlet</servlet-name>
17<servlet-class>com.durgasoft.servlets.LoginServlet</servlet-class>
18</servlet>
19<servlet-mapping>
20<servlet-name>LoginServlet</servlet-name>
21<url-pattern>/login</url-pattern>
22</servlet-mapping>
23</web-app>
24

log4j.properties — LoginServlet.java

 log4j.rootLogger = ALL, FILE  log4j.appender.FILE = org.apache.log4j.FileAppender  log4j.appender.FILE.file = E:/loggers/logs.txt  #log4j.appender.FILE.datePattern = '.'dd-MM-yyyy-HH-mm  log4j.appender.FILE.layout = org.apache.log4j.PatternLayout  #log4j.appender.FILE.layout = org.apache.log4j.PatternLayout  log4j.appender.FILE.layout.conversionPattern = %d{dd/MM/YYYY HH:mm:SS} %-C %p

%L : %m%n

Example49
JCode Cell
1 
2package com.durgasoft.servlets;
3 
4import java.io.IOException;
5 
6import javax.servlet.RequestDispatcher;
7import javax.servlet.ServletException;
8import javax.servlet.http.HttpServlet;
9import javax.servlet.http.HttpServletRequest;
10import javax.servlet.http.HttpServletResponse;
11 
12import org.apache.log4j.Logger;
13 
14import com.durgasoft.service.UserService;
15public class LoginServlet extends HttpServlet {
16private static final long serialVersionUID = 1L;
17public static Logger logger = Logger.getLogger(LoginServlet.class);
18protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19logger.info("LoginServlet Started-doPost()");
20String uname = request.getParameter("uname");
21String upwd = request.getParameter("upwd");
22logger.info("User Request Recieved with User Name :"+uname+" With password :"+upwd);
23 
24UserService userService = new UserService();
25String status = userService.checkLogin(uname, upwd);
26 
27RequestDispatcher reqDispatcher = null;
28if(status.equals("success")) {
29 reqDispatcher = request.getRequestDispatcher("success.html");
30 reqDispatcher.forward(request, response);
31}else {
32 reqDispatcher = request.getRequestDispatcher("failure.html");
33 reqDispatcher.forward(request, response);
34}
35logger.info("Login Status :"+status);
36logger.info("End of LoginServlet");
37}
38}
39

log4j.properties — UserService.java

Example50
JCode Cell
1 
2package com.durgasoft.service;
3import org.apache.log4j.Logger;
4 
5import com.durgasoft.servlets.LoginServlet;
6 
7public class UserService {
8static Logger logger = Logger.getLogger(UserService.class);
9String status = "";
10public String checkLogin(String uname, String upwd) {
11 
12 
13logger.debug("UserService : checkLogin() Method started");
14if(uname.equals("durga") && upwd.equals("durga")) {
15 logger.info("UserService :Login Success");
16 status = "success";
17}else {
18 logger.info("USerService :Login Failure");
19 status = "failure";
20}
21logger.info("USerService :End of CheckLogin()");
22return status;
23}
24}
25
📝 Key Takeaways
  • Key ideas of Spring - Log4j Integration explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end