Need of Log4J
Need of Log4J
NEED OF LOG4J
BUG/Problem:- After Application is developed then it will be handover to End Client/Customer.
At the time of Running Application some problems may occur while processing a request. In
programming concept it is called as Exception.
These problems try to identify at the time of development to avoid few. Some will be
handled once they are occurred. Those are analyzed and solved by developer. Give priority to
Avoid problems if not handle the problems.
1. Validations : At UI page like Register, Data Edit, Login, Feedback form, Comment etc.. at
these levels we must use Java Script or equal Programming to avoid invalid input. Example:-
Examples : -
1
Log4J [Notes By Raghu Sir] Sathya Technologies, Ameerpet, Hyd.
int arr[]={....};
if(arr.length > 4){
sysout(arr[4]);
}else {
sysout("Array Size is less");
}
iv) List<Employee> has Employee objects read 1st index employee and find that employee
object empName length
code
List<Employee> empList=....
Employee e=list.get(0);
String empName=e.getEmpName();
int len=empName.length();
above code can be written as.....
if(empList!=null && empList.size>0 && empList.get(0)!=null ){
Employee e=list.get(0);
if(e!=null && e.getEmpName()!=null ) {
int len=e.getEmpName().length();
}
}
____________________________________________________________________________
3. Error Pages in Web Applications:- If server has encountered any problem then it will throw
An equal HTTP Error. Example 404-Page Not Found, 500-Internal server Error, 400-Syntax
Error, 405-Method Not Allowed, 401-UnAuthorized etc...
To show one simple message to end user we must define JSP/HTML page and make
them as isErrorPage="true" and configure in web.xml as
2
Log4J [Notes By Raghu Sir] Sathya Technologies, Ameerpet, Hyd.
<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.NullPoniterException</exception-type>
<location>/showError.jsp</location>
</error-page>
3
Log4J [Notes By Raghu Sir] Sathya Technologies, Ameerpet, Hyd.
Log4J
1. Logger (LOG) Object: This object must be created inside the class as a instance variable. It is
used to enable Log4J service to current class. If this object is not created in the class then Log4J
concpet will not applicable(will not work)for that class It has 5 priority methods with names
(along with order)
a. debug(msg) : It prints a message with data. It is used to print a final result of process.
Like EmpId after saved is : 2362.
b. info(msg) : It is used to print a simple message. Like process state-I done, if block end.
Email sent etc..
4
Log4J [Notes By Raghu Sir] Sathya Technologies, Ameerpet, Hyd.
c. warn(msg): It is used to print warning messages. Like Collection is not with Generic, local
variable not used, resource not closed etc...
d. error(msg): It is used to print Exceptions like NullPointer, ArrayIndex, SQLException etc..
e. fatal(mgs) : It indicates very high level problem. Like Server/DB Down, Connection
timeout, Network broken, Class Not Found etc...
OFF is used to disable Log4J concept in application. Log4J code need to be deleted.
__________________________________________________________________________
2. Appender : It will provide details for "Where to print Message?". Means in what type of
memories, messages must be stored. To write Logger Statements to
____________________________________________________________________________
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
Step#3 Create one class under "src/main/java" and write Log4J code.
ex: code
package com.app;
import org.apache.log4j.Appender;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
Note:
1. To Create "Logger" class object to current class use static factory method getLogger(_.class).
It returns Logger Object and enable the Log4J to current class.
2. Create a Layout(Abstract Class) object using it's implemented classes, list given below
a. SimplLayout (C)
b. XMLLayout (C)
c. HTMLLayout (C)
6
Log4J [Notes By Raghu Sir] Sathya Technologies, Ameerpet, Hyd.
d. PatternLayout(C)
3. Create Appender(I) object using it's implemented classes and also provide layout details to
Appender object.
a. ConsoleAppender (C)
b. FileAppender (C)
c. JdbcAppender (C)
d. SmtpAppender (C)
4. At last Appender object must be added to Logger Object then only it is considered, by using
log.addAppender() method.
_______________________________________________________________________
2. HTMLLayout : This class provides message in HTML format. To see full output of this. Copy
output to .html file
Example Code:
package com.app;
import org.apache.log4j.Appender;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.HTMLLayout;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
7
Log4J [Notes By Raghu Sir] Sathya Technologies, Ameerpet, Hyd.
log.debug("Hello");
log.info("Hello");
log.warn("Hello");
log.error("Hello");
log.fatal("Hello");
}
}
Example: screen
3. XMLLayout: It prints log messages in XML format. In above code modify Layout as XMLLayout
and run as same.
Example Code:
package com.app;
import org.apache.log4j.Appender;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.XMLLayout;
8
Log4J [Notes By Raghu Sir] Sathya Technologies, Ameerpet, Hyd.
log.debug("Hello");
log.info("Hello");
log.warn("Hello");
log.error("Hello");
log.fatal("Hello");
}
}
Output Looks as :
4. PatternLayout : This class provides output pattern for a message that contains date, time,
class, method, line number, thread name, message etc..
Observe Some example patterns given below, for complete details click on below link
(https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html)
9
Log4J [Notes By Raghu Sir] Sathya Technologies, Ameerpet, Hyd.
a)Date&Time pattern
%C = Class Name
%M = Method Name
%m = Message
%p = Priority method name(DEBUG,INFO..)
%L = Line Number
%l = Line number with Link
%n = New Line(next line)
%r = time in milli sec.
%% = To print one '%' symbol.
we can also use symbols like - [] , /
One Example Pattern with all matching "%d-%C[%M] : {%p}=%m<%L> %n "
_________________________________________________________________________
Appender:- An appender provides the destination of log message. Here example appenders
are
a) ConsoleAppender
b) FileAppender
10
Log4J [Notes By Raghu Sir] Sathya Technologies, Ameerpet, Hyd.
c) JdbcAppender
d) SmtpAppender
Example of FileAppender:-
package com.app;
import org.apache.log4j.Appender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.HTMLLayout;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
log.debug("Hello");
log.info("Hello");
log.warn("Hello");
log.error("Hello");
log.fatal("Hello");
}
}
log4j.properties
log4j.properties file: This file is used to specify all the configuration details of Log4J. Especially
like Appender Details and Layout Details with Patterns and also root Logger details. This File
contains details in key=value format (.properties). Data will be shown in below order like
1. rootLogger
2. appenders
3. layouts
11
Log4J [Notes By Raghu Sir] Sathya Technologies, Ameerpet, Hyd.
______________________________________________________________________________
Test class:-
package com.app;
import org.apache.log4j.Logger;
public class Product {
private static Logger log=Logger.getLogger(Product.class);
public static void main(String[] srs){
log.debug("Hello");
log.info("Hello");
12
Log4J [Notes By Raghu Sir] Sathya Technologies, Ameerpet, Hyd.
log.warn("Hello");
log.error("Hello");
log.fatal("Hello");
}
}
output:
1. debug() : to specify a message with value (message with result after operation)
2. info() : to indicate current state (block end, method started , service finished, email sent
etc..)
3. warn() : to provide warning message (Variable not used, List has no generic, connection
not closed)..
4. error/fatal : used in catch blocks. Here error - used for unchecked exception and fatal -
checked exception in general
package com.app.controller;
@Controller
public class HomeController {
private static Logger log=Logger.getLogger(HomeController.class);
@RequestMapping("/url")
public String saveEmp(...){
log.info("Save Method started");
try{
log.info("Before save employee..");
int empId=service.save(emp);
log.debug("emp saved with id :"+empId);
}catch(Exception e){
log.error(e); // log.fatal(e);
13
Log4J [Notes By Raghu Sir] Sathya Technologies, Ameerpet, Hyd.
}
log.warn("EMPID not used in program");
log.info("save service is at end");
return "Home";
}
}
Log4j Examples
pom.xml (to run all below examples)
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sathyatech</groupId>
<artifactId>log4jexample</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
</project>
14
Log4J [Notes By Raghu Sir] Sathya Technologies, Ameerpet, Hyd.
Step#1 : Define one Test class with example code with log methods.
package com.app;
import org.apache.log4j.Logger;
public class Product {
private static Logger log=Logger.getLogger(Product.class);
public static void main(String[] srs){
log.debug("Hello");
log.info("Hello");
log.warn("Hello");
log.error("Hello");
log.fatal("Hello");
}
}
log4j.propertie:
15
Log4J [Notes By Raghu Sir] Sathya Technologies, Ameerpet, Hyd.
Folder Structure:-
_____________________________________________________________________________
package com.app;
import org.apache.log4j.Logger;
public class Product {
private static Logger log=Logger.getLogger(Product.class);
public static void main(String[] srs){
log.debug("Hello");
log.info("Hello");
log.warn("Hello");
log.error("Hello");
log.fatal("Hello");
}
}
16
Log4J [Notes By Raghu Sir] Sathya Technologies, Ameerpet, Hyd.
log4j.properties
# Root logger option
log4j.rootLogger=DEBUG, file
# Redirect log messages to a log file
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=logs/myapp.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %p %c:%L - %m%n
Step#1 : Define one Test class with example code with log methods.
package com.app;
import org.apache.log4j.Logger;
public class Product {
private static Logger log=Logger.getLogger(Product.class);
public static void main(String[] srs){
log.debug("Hello");
log.info("Hello");
log.warn("Hello");
log.error("Hello");
log.fatal("Hello");
}
}
Step#2 Create this table before you run example, all the logs will be stored in below table
CREATE TABLE LOGS (
METHOD VARCHAR(20) NOT NULL,
DATED DATETIME NOT NULL,
LOGGER VARCHAR(50) NOT NULL,
LEVEL VARCHAR(10) NOT NULL,
MESSAGE VARCHAR(1000) NOT NULL
);
17
Log4J [Notes By Raghu Sir] Sathya Technologies, Ameerpet, Hyd.
log4j.properties
# Root logger option
log4j.rootLogger=DEBUG, db
_____________________________________________________________________________
Step#1 : Define one Test class with example code with log methods.
package com.app;
import org.apache.log4j.Logger;
public class Product {
private static Logger log=Logger.getLogger(Product.class);
public static void main(String[] srs){
log.debug("Hello");
log.info("Hello");
log.warn("Hello");
log.error("Hello");
log.fatal("Hello");
}
}
18
Log4J [Notes By Raghu Sir] Sathya Technologies, Ameerpet, Hyd.
** Modify user Name and password before you run this application
# Root logger option
log4j.rootLogger=DEBUG, email
#configuring the SMTP appender
log4j.appender.email=org.apache.log4j.net.SMTPAppender
log4j.appender.email.SMTPHost=smtp.gmail.com
[email protected]
log4j.appender.email.SMTPPassword=abdeyhfk@33
[email protected]
log4j.appender.email.To=<your email id>@gmail.com
log4j.appender.email.Subject=Log of messages
log4j.appender.email.Threshold=DEBUG
log4j.appender.email.layout=org.apache.log4j.PatternLayout
log4j.appender.email.layout.ConversionPattern= %m %n
-Dmail.smtp.starttls.enable=true
19
Log4J [Notes By Raghu Sir] Sathya Technologies, Ameerpet, Hyd.
Step#4 Run above Test class Product.java (ctrl+F11) to see output. Or Click on Run Option
shown in above screen
20