SlideShare ist ein Scribd-Unternehmen logo
1 von 46
Logging with Log4j
KAMAL METTANANDA
SOFTWARE ARCHITECT
ACCELERITE – PERSISTENT SYSTEMS
@KAMALMETTANANDA
Who am I?
B.Sc. in 2004 University of Moratuwa
Masters in computer sciences 2012
10+ years of industry experience
Working as an Architect in Accelerite
Author of www.digizol.com
2KAMAL METTANANDA
Agenda
What is logging
• Why logging
• How to log
Log4j 1.2
• Format (Layouts)
• Handler (Appenders)
• Logger (Categories)
Log4j 2
Java logging API
Learn further
3KAMAL METTANANDA
Objective
Make sure ALL
brothers & sisters
know how to use log4j
in a Java project
4KAMAL METTANANDA
What is logging
Pile of logs in Indonesia. Photos by Rhett Butler
“Logging, or
commercial
logging,
involves
cutting trees
for sale as
timber or
pulp”
• mongabay.com
5KAMAL METTANANDA
What is logging
“Logging refers to the recording of
activity. Logging is a common issue for
development teams. Several frameworks
ease and standardize the process of
logging for the Java platform.”
• wikipedia
6KAMAL METTANANDA
Why logging
Troubleshoot by finding
What has
happened
What is
happening
7KAMAL METTANANDA
What to log
• Meaningful message
• State of objects
• Exceptions
• Class name
• Time of logging
• Thread/invoker
Useful
information
to
troubleshoot
8KAMAL METTANANDA
How to log
•Most simplest
•Not enough information
•Unable to switch on/off
System.out.print()
9KAMAL METTANANDA
How to log
• A lot of required information
• Simple enable/disable mechanism
• Configurable without code changes
• Multiple destinations
Use a dedicated logging library
10KAMAL METTANANDA
Logging libraries
Log4j v1.2
Log4j v2
JUL - Java Logging API
Logback
Commons logging
SLF4J
11KAMAL METTANANDA
Log4j 1.2
APACHE SOFTWARE
12KAMAL METTANANDA
Environment Setup
Install Java
Install Eclipse
Import Projects
• From https://github.com/lkamal/log4j-
workshop
13KAMAL METTANANDA
Log4j 1.2
Started in 1996
• Released in around 2000
Free and Open source
• Apache Licensed – 2.0
Latest version 1.2.17
14KAMAL METTANANDA
Enabling Log4j in project
• log4j-1.2.x.jarJar file
• log4j.properties OR
• log4j.xml
Configuration
file
• org.apache.log4j.Logger
Logger
instance
15KAMAL METTANANDA
Hello World sample
• 01_helloworld_sysout
Hello world
with Sysout
• 02_helloworld_log4j
Hello world
with log4j
16KAMAL METTANANDA
Log4j Components
Logger
Appender
Layout
17KAMAL METTANANDA
Logger instance by name
org.apache.log4j.Logger =
org.apache.log4j.Logger.getLogger(Class)
org.apache.log4j.Logger.getLogger(String)
18KAMAL METTANANDA
Logger Instance
public class MainLog4j {
private static Logger logger =
Logger.getLogger(MainLog4j.class);
…
}
19KAMAL METTANANDA
Simple log4j.properties file
# top level config=logging level, appenders
log4j.rootLogger=INFO, console
# console appender configurations
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.SimpleLayout
20KAMAL METTANANDA
Calculator sample
• 03_calculator_sysout
Calculator
with Sysout
• 04_calculator_log4j
Calculator
with log4j
21KAMAL METTANANDA
Log level - Priority
TRACE
DEBUG
INFO
WARN
ERROR
FATAL
LogFilterSize
MessagePriority
22KAMAL METTANANDA
Log Level - Usage
Least priority messageslogger.trace()
logger.debug()
logger.info()
logger.warn()
logger.error()
Highest priority messageslogger.fatal()
23KAMAL METTANANDA
Log Level - log4j.properties
log4j.rootLogger=<LEVEL>, <Appenders>
•e.g:
•DEBUG, console
•INFO , console
•ERROR , console
24KAMAL METTANANDA
Calculator with log levels
• 05_calculator_log4j_levels
Calculator
with log
levels
25KAMAL METTANANDA
log4j.properties - file content
log4j.rootLogger
Log level
Appenders
log4j.appender
Destination
Layout
log4j.logger
Package
Log Level
Appenders
26KAMAL METTANANDA
Layout - Format
• org.apache.log4j.SimpleLayout
• INFO - message
• org.apache.log4j.HTMLLayout
• HTML table row per log line
• org.apache.log4j.xml.XMLLayout
• XML tag per log line
• org.apache.log4j.PatternLayout
• Mostly used
log4j.appender.<appender>.layout
property value
27KAMAL METTANANDA
Calculator with log formatting
• 06_calculator_log4j_format
Calculator
with
xml/html logs
• 07_calculator_log4j_patterlayout
Calculator
with Pattern
Layout logs
28KAMAL METTANANDA
log4j.properties - file content
log4j.rootLogger
Log level
Appenders
log4j.appender
Destination
Layout
log4j.logger
Package
Log Level
Appenders
29KAMAL METTANANDA
Appenders – Output Handlers
• A name must be given for <appender>
• org.apache.log4j.ConsoleAppender
• System out / console
• org.apache.log4j.FileAppender
• To a given file
• org.apache.log4j.RollingFileAppender
• When one file is full – move to next
• org.apache.log4j.DailyRollingFileAppender
• Daily write to a new file
log4j.appender.<appender> property
30KAMAL METTANANDA
Appenders – Log Level
• Required log level can be configured by
overriding root level.
• e.g.:
• log4.appender.console.Threshold=INFO
log4j.appender.<appender>.Threshold
31KAMAL METTANANDA
Calculator with appenders
• 08_calculator_log4j_appe
nders
Calculator
with
multiple log
destinations
32KAMAL METTANANDA
log4j.properties - file content
log4j.rootLogger
Log level
Appenders
log4j.appender
Destination
Layout
log4j.logger
Name
Log Level
Appenders
33KAMAL METTANANDA
Logger - Categories
log4j.logger.<logger-name>
property
• Log level
• Restrict the log level for the package
• Appender
• Restrict the appender for the logs
34KAMAL METTANANDA
Calculator with Categories
• 09_calculator_log4j_categories
Calculator
with
different
loggers
35KAMAL METTANANDA
Logging Exceptions
• logger.trace(msg, exception)
• logger.debug(msg, exception)
• logger.info(msg, exception)
• logger.warn(msg, exception)
• logger.error(msg, exception)
• logger.fatal(msg, exception)
Exceptions
can be
logged
with stack
trace
36KAMAL METTANANDA
Calculator with exception
• 10_calculator_log4j_exception
Calculator
with
exception
37KAMAL METTANANDA
Log4j – Performance hit
Minimize with methods like
isDebugEnabled() isInfoEnabled()
Smaller performance hit
38KAMAL METTANANDA
Log4j – Performance hit
if (logger.isDebugEnabled()) {
logger.debug(“method invoked ” + result);
}
if (logger.isInfoEnabled()) {
logger.info(“method invoked ” + result);
}
39KAMAL METTANANDA
Log4j 1.2 Summary
Supports logging by
simple on/off
mechanism
required information
multiple destinations
Needs only 3 items
Library
Configuration file
Logger instances
40KAMAL METTANANDA
Log4j 2
Performance improved against log4j 1.2
Configuration via xml, not properties file
Migration tool for 1.2 to 2 available
Not by original author
• Disclaimer: I am the founder of log4j, slf4j and logback projects but
unaffiliated with log4j 2.0. As I understand it, notwithstanding its
name, log4j 2.0 is very different than log4j 1.x. As far as the user API is
concerned, log4j 2.0 is largely incompatible with log4j 1.x.
• stackoverflow.com/a/12095467/2581128
41KAMAL METTANANDA
JUL - Java logging API
Java itself has
a logging API
java.util.logging.Logger
But was too
late to be born
42KAMAL METTANANDA
Logging libraries
© zeroturnaround.com
43KAMAL METTANANDA
Learn further
Logback
Log4j 2
JUL - Java logging API
Commons-logging
SLF4j
44KAMAL METTANANDA
45KAMAL METTANANDA
Thank you

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
Web search Technologies
Web search TechnologiesWeb search Technologies
Web search Technologies
 
What is an API
What is an APIWhat is an API
What is an API
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
OpenAPI 3.0, And What It Means for the Future of Swagger
OpenAPI 3.0, And What It Means for the Future of SwaggerOpenAPI 3.0, And What It Means for the Future of Swagger
OpenAPI 3.0, And What It Means for the Future of Swagger
 
Web Applications and Deployment
Web Applications and DeploymentWeb Applications and Deployment
Web Applications and Deployment
 
API
APIAPI
API
 
Postman.ppt
Postman.pptPostman.ppt
Postman.ppt
 
Api presentation
Api presentationApi presentation
Api presentation
 
Java servlets
Java servletsJava servlets
Java servlets
 
Api testing bible using postman
Api testing bible using postmanApi testing bible using postman
Api testing bible using postman
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Web application framework
Web application frameworkWeb application framework
Web application framework
 
Rest assured
Rest assuredRest assured
Rest assured
 
REST API Design & Development
REST API Design & DevelopmentREST API Design & Development
REST API Design & Development
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
 
Introduction to Apache solr
Introduction to Apache solrIntroduction to Apache solr
Introduction to Apache solr
 
Android share preferences
Android share preferencesAndroid share preferences
Android share preferences
 
An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)An Introduction of Node Package Manager (NPM)
An Introduction of Node Package Manager (NPM)
 

Andere mochten auch

Log4j Logging Mechanism
Log4j Logging MechanismLog4j Logging Mechanism
Log4j Logging MechanismKunal Dabir
 
SLF4J (Simple Logging Facade for Java)
SLF4J (Simple Logging Facade for Java)SLF4J (Simple Logging Facade for Java)
SLF4J (Simple Logging Facade for Java)Guo Albert
 
LOGBack and SLF4J
LOGBack and SLF4JLOGBack and SLF4J
LOGBack and SLF4Jjkumaranc
 
Exception handling and logging best practices
Exception handling and logging best practicesException handling and logging best practices
Exception handling and logging best practicesAngelin R
 
logback 세미나 발표자료
logback 세미나 발표자료logback 세미나 발표자료
logback 세미나 발표자료JungGeun Lee
 
Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Angelin R
 
스프링 어플리케이션의 문제해결사례와 안티패턴
스프링 어플리케이션의 문제해결사례와 안티패턴스프링 어플리케이션의 문제해결사례와 안티패턴
스프링 어플리케이션의 문제해결사례와 안티패턴Sanghyuk Jung
 
스프링시큐리티와 소셜연습 이해를 위한 글
스프링시큐리티와 소셜연습 이해를 위한 글스프링시큐리티와 소셜연습 이해를 위한 글
스프링시큐리티와 소셜연습 이해를 위한 글라한사 아
 
아라한사의 스프링 시큐리티 정리
아라한사의 스프링 시큐리티 정리아라한사의 스프링 시큐리티 정리
아라한사의 스프링 시큐리티 정리라한사 아
 
스프링 부트와 로깅
스프링 부트와 로깅스프링 부트와 로깅
스프링 부트와 로깅Keesun Baik
 
스프링 시큐리티 구조 이해
스프링 시큐리티 구조 이해스프링 시큐리티 구조 이해
스프링 시큐리티 구조 이해beom kyun choi
 
Spring boot 를 적용한 전사모니터링 시스템 backend 개발 사례
Spring boot 를 적용한 전사모니터링 시스템 backend 개발 사례Spring boot 를 적용한 전사모니터링 시스템 backend 개발 사례
Spring boot 를 적용한 전사모니터링 시스템 backend 개발 사례Jemin Huh
 
Javaのログ出力: 道具と考え方
Javaのログ出力: 道具と考え方Javaのログ出力: 道具と考え方
Javaのログ出力: 道具と考え方Taku Miyakawa
 

Andere mochten auch (18)

Log4j Logging Mechanism
Log4j Logging MechanismLog4j Logging Mechanism
Log4j Logging Mechanism
 
LOG4J
LOG4JLOG4J
LOG4J
 
Log4j in 8 slides
Log4j in 8 slidesLog4j in 8 slides
Log4j in 8 slides
 
SLF4J (Simple Logging Facade for Java)
SLF4J (Simple Logging Facade for Java)SLF4J (Simple Logging Facade for Java)
SLF4J (Simple Logging Facade for Java)
 
LOGBack and SLF4J
LOGBack and SLF4JLOGBack and SLF4J
LOGBack and SLF4J
 
SLF4J+Logback
SLF4J+LogbackSLF4J+Logback
SLF4J+Logback
 
SLF4J Explained........
SLF4J Explained........SLF4J Explained........
SLF4J Explained........
 
Exception handling and logging best practices
Exception handling and logging best practicesException handling and logging best practices
Exception handling and logging best practices
 
logback 세미나 발표자료
logback 세미나 발표자료logback 세미나 발표자료
logback 세미나 발표자료
 
Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)
 
스프링 어플리케이션의 문제해결사례와 안티패턴
스프링 어플리케이션의 문제해결사례와 안티패턴스프링 어플리케이션의 문제해결사례와 안티패턴
스프링 어플리케이션의 문제해결사례와 안티패턴
 
스프링시큐리티와 소셜연습 이해를 위한 글
스프링시큐리티와 소셜연습 이해를 위한 글스프링시큐리티와 소셜연습 이해를 위한 글
스프링시큐리티와 소셜연습 이해를 위한 글
 
아라한사의 스프링 시큐리티 정리
아라한사의 스프링 시큐리티 정리아라한사의 스프링 시큐리티 정리
아라한사의 스프링 시큐리티 정리
 
스프링 부트와 로깅
스프링 부트와 로깅스프링 부트와 로깅
스프링 부트와 로깅
 
스프링 시큐리티 구조 이해
스프링 시큐리티 구조 이해스프링 시큐리티 구조 이해
스프링 시큐리티 구조 이해
 
Spring boot 를 적용한 전사모니터링 시스템 backend 개발 사례
Spring boot 를 적용한 전사모니터링 시스템 backend 개발 사례Spring boot 를 적용한 전사모니터링 시스템 backend 개발 사례
Spring boot 를 적용한 전사모니터링 시스템 backend 개발 사례
 
Spring Boot 소개
Spring Boot 소개Spring Boot 소개
Spring Boot 소개
 
Javaのログ出力: 道具と考え方
Javaのログ出力: 道具と考え方Javaのログ出力: 道具と考え方
Javaのログ出力: 道具と考え方
 

Ähnlich wie Configure Logging with Log4j

Logging with Logback in Scala
Logging with Logback in ScalaLogging with Logback in Scala
Logging with Logback in ScalaKnoldus Inc.
 
Distributed Logging System Using Elasticsearch Logstash,Beat,Kibana Stack and...
Distributed Logging System Using Elasticsearch Logstash,Beat,Kibana Stack and...Distributed Logging System Using Elasticsearch Logstash,Beat,Kibana Stack and...
Distributed Logging System Using Elasticsearch Logstash,Beat,Kibana Stack and...Sanjog Kumar Dash
 
Logging Application Behavior to MongoDB
Logging Application Behavior to MongoDBLogging Application Behavior to MongoDB
Logging Application Behavior to MongoDBRobert Stewart
 
Graylog for open stack 3 steps to know why
Graylog for open stack    3 steps to know whyGraylog for open stack    3 steps to know why
Graylog for open stack 3 steps to know whyMạnh Đinh
 
Infinum Android Talks #14 - Log4j
Infinum Android Talks #14 - Log4jInfinum Android Talks #14 - Log4j
Infinum Android Talks #14 - Log4jInfinum
 
Logging and Exception
Logging and ExceptionLogging and Exception
Logging and ExceptionAzeem Mumtaz
 
Meetup milano #4 log management and anypoint advanced monitoring
Meetup milano #4   log management and anypoint advanced monitoringMeetup milano #4   log management and anypoint advanced monitoring
Meetup milano #4 log management and anypoint advanced monitoringGonzalo Marcos Ansoain
 
Java Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4jJava Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4jRajiv Gupta
 
Logging in Scala
Logging in ScalaLogging in Scala
Logging in ScalaJohn Nestor
 
Extreme Replication - RMOUG Presentation
Extreme Replication - RMOUG PresentationExtreme Replication - RMOUG Presentation
Extreme Replication - RMOUG PresentationBobby Curtis
 

Ähnlich wie Configure Logging with Log4j (20)

Logging
LoggingLogging
Logging
 
Logging with Logback in Scala
Logging with Logback in ScalaLogging with Logback in Scala
Logging with Logback in Scala
 
Distributed Logging System Using Elasticsearch Logstash,Beat,Kibana Stack and...
Distributed Logging System Using Elasticsearch Logstash,Beat,Kibana Stack and...Distributed Logging System Using Elasticsearch Logstash,Beat,Kibana Stack and...
Distributed Logging System Using Elasticsearch Logstash,Beat,Kibana Stack and...
 
Log4e
Log4eLog4e
Log4e
 
Logging Application Behavior to MongoDB
Logging Application Behavior to MongoDBLogging Application Behavior to MongoDB
Logging Application Behavior to MongoDB
 
Log4e
Log4eLog4e
Log4e
 
Java 9 and Project Jigsaw
Java 9 and Project JigsawJava 9 and Project Jigsaw
Java 9 and Project Jigsaw
 
Log
LogLog
Log
 
Graylog for open stack 3 steps to know why
Graylog for open stack    3 steps to know whyGraylog for open stack    3 steps to know why
Graylog for open stack 3 steps to know why
 
Log4j slideshare
Log4j slideshareLog4j slideshare
Log4j slideshare
 
Logger
LoggerLogger
Logger
 
Graylog for open stack 3 steps to know why
Graylog for open stack    3 steps to know whyGraylog for open stack    3 steps to know why
Graylog for open stack 3 steps to know why
 
Infinum Android Talks #14 - Log4j
Infinum Android Talks #14 - Log4jInfinum Android Talks #14 - Log4j
Infinum Android Talks #14 - Log4j
 
Logging and Exception
Logging and ExceptionLogging and Exception
Logging and Exception
 
Logback
LogbackLogback
Logback
 
Meetup milano #4 log management and anypoint advanced monitoring
Meetup milano #4   log management and anypoint advanced monitoringMeetup milano #4   log management and anypoint advanced monitoring
Meetup milano #4 log management and anypoint advanced monitoring
 
Java Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4jJava Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4j
 
Logging in Scala
Logging in ScalaLogging in Scala
Logging in Scala
 
Java logging
Java loggingJava logging
Java logging
 
Extreme Replication - RMOUG Presentation
Extreme Replication - RMOUG PresentationExtreme Replication - RMOUG Presentation
Extreme Replication - RMOUG Presentation
 

Kürzlich hochgeladen

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 

Kürzlich hochgeladen (20)

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 

Configure Logging with Log4j

  • 1. Logging with Log4j KAMAL METTANANDA SOFTWARE ARCHITECT ACCELERITE – PERSISTENT SYSTEMS @KAMALMETTANANDA
  • 2. Who am I? B.Sc. in 2004 University of Moratuwa Masters in computer sciences 2012 10+ years of industry experience Working as an Architect in Accelerite Author of www.digizol.com 2KAMAL METTANANDA
  • 3. Agenda What is logging • Why logging • How to log Log4j 1.2 • Format (Layouts) • Handler (Appenders) • Logger (Categories) Log4j 2 Java logging API Learn further 3KAMAL METTANANDA
  • 4. Objective Make sure ALL brothers & sisters know how to use log4j in a Java project 4KAMAL METTANANDA
  • 5. What is logging Pile of logs in Indonesia. Photos by Rhett Butler “Logging, or commercial logging, involves cutting trees for sale as timber or pulp” • mongabay.com 5KAMAL METTANANDA
  • 6. What is logging “Logging refers to the recording of activity. Logging is a common issue for development teams. Several frameworks ease and standardize the process of logging for the Java platform.” • wikipedia 6KAMAL METTANANDA
  • 7. Why logging Troubleshoot by finding What has happened What is happening 7KAMAL METTANANDA
  • 8. What to log • Meaningful message • State of objects • Exceptions • Class name • Time of logging • Thread/invoker Useful information to troubleshoot 8KAMAL METTANANDA
  • 9. How to log •Most simplest •Not enough information •Unable to switch on/off System.out.print() 9KAMAL METTANANDA
  • 10. How to log • A lot of required information • Simple enable/disable mechanism • Configurable without code changes • Multiple destinations Use a dedicated logging library 10KAMAL METTANANDA
  • 11. Logging libraries Log4j v1.2 Log4j v2 JUL - Java Logging API Logback Commons logging SLF4J 11KAMAL METTANANDA
  • 13. Environment Setup Install Java Install Eclipse Import Projects • From https://github.com/lkamal/log4j- workshop 13KAMAL METTANANDA
  • 14. Log4j 1.2 Started in 1996 • Released in around 2000 Free and Open source • Apache Licensed – 2.0 Latest version 1.2.17 14KAMAL METTANANDA
  • 15. Enabling Log4j in project • log4j-1.2.x.jarJar file • log4j.properties OR • log4j.xml Configuration file • org.apache.log4j.Logger Logger instance 15KAMAL METTANANDA
  • 16. Hello World sample • 01_helloworld_sysout Hello world with Sysout • 02_helloworld_log4j Hello world with log4j 16KAMAL METTANANDA
  • 18. Logger instance by name org.apache.log4j.Logger = org.apache.log4j.Logger.getLogger(Class) org.apache.log4j.Logger.getLogger(String) 18KAMAL METTANANDA
  • 19. Logger Instance public class MainLog4j { private static Logger logger = Logger.getLogger(MainLog4j.class); … } 19KAMAL METTANANDA
  • 20. Simple log4j.properties file # top level config=logging level, appenders log4j.rootLogger=INFO, console # console appender configurations log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.layout=org.apache.log4j.SimpleLayout 20KAMAL METTANANDA
  • 21. Calculator sample • 03_calculator_sysout Calculator with Sysout • 04_calculator_log4j Calculator with log4j 21KAMAL METTANANDA
  • 22. Log level - Priority TRACE DEBUG INFO WARN ERROR FATAL LogFilterSize MessagePriority 22KAMAL METTANANDA
  • 23. Log Level - Usage Least priority messageslogger.trace() logger.debug() logger.info() logger.warn() logger.error() Highest priority messageslogger.fatal() 23KAMAL METTANANDA
  • 24. Log Level - log4j.properties log4j.rootLogger=<LEVEL>, <Appenders> •e.g: •DEBUG, console •INFO , console •ERROR , console 24KAMAL METTANANDA
  • 25. Calculator with log levels • 05_calculator_log4j_levels Calculator with log levels 25KAMAL METTANANDA
  • 26. log4j.properties - file content log4j.rootLogger Log level Appenders log4j.appender Destination Layout log4j.logger Package Log Level Appenders 26KAMAL METTANANDA
  • 27. Layout - Format • org.apache.log4j.SimpleLayout • INFO - message • org.apache.log4j.HTMLLayout • HTML table row per log line • org.apache.log4j.xml.XMLLayout • XML tag per log line • org.apache.log4j.PatternLayout • Mostly used log4j.appender.<appender>.layout property value 27KAMAL METTANANDA
  • 28. Calculator with log formatting • 06_calculator_log4j_format Calculator with xml/html logs • 07_calculator_log4j_patterlayout Calculator with Pattern Layout logs 28KAMAL METTANANDA
  • 29. log4j.properties - file content log4j.rootLogger Log level Appenders log4j.appender Destination Layout log4j.logger Package Log Level Appenders 29KAMAL METTANANDA
  • 30. Appenders – Output Handlers • A name must be given for <appender> • org.apache.log4j.ConsoleAppender • System out / console • org.apache.log4j.FileAppender • To a given file • org.apache.log4j.RollingFileAppender • When one file is full – move to next • org.apache.log4j.DailyRollingFileAppender • Daily write to a new file log4j.appender.<appender> property 30KAMAL METTANANDA
  • 31. Appenders – Log Level • Required log level can be configured by overriding root level. • e.g.: • log4.appender.console.Threshold=INFO log4j.appender.<appender>.Threshold 31KAMAL METTANANDA
  • 32. Calculator with appenders • 08_calculator_log4j_appe nders Calculator with multiple log destinations 32KAMAL METTANANDA
  • 33. log4j.properties - file content log4j.rootLogger Log level Appenders log4j.appender Destination Layout log4j.logger Name Log Level Appenders 33KAMAL METTANANDA
  • 34. Logger - Categories log4j.logger.<logger-name> property • Log level • Restrict the log level for the package • Appender • Restrict the appender for the logs 34KAMAL METTANANDA
  • 35. Calculator with Categories • 09_calculator_log4j_categories Calculator with different loggers 35KAMAL METTANANDA
  • 36. Logging Exceptions • logger.trace(msg, exception) • logger.debug(msg, exception) • logger.info(msg, exception) • logger.warn(msg, exception) • logger.error(msg, exception) • logger.fatal(msg, exception) Exceptions can be logged with stack trace 36KAMAL METTANANDA
  • 37. Calculator with exception • 10_calculator_log4j_exception Calculator with exception 37KAMAL METTANANDA
  • 38. Log4j – Performance hit Minimize with methods like isDebugEnabled() isInfoEnabled() Smaller performance hit 38KAMAL METTANANDA
  • 39. Log4j – Performance hit if (logger.isDebugEnabled()) { logger.debug(“method invoked ” + result); } if (logger.isInfoEnabled()) { logger.info(“method invoked ” + result); } 39KAMAL METTANANDA
  • 40. Log4j 1.2 Summary Supports logging by simple on/off mechanism required information multiple destinations Needs only 3 items Library Configuration file Logger instances 40KAMAL METTANANDA
  • 41. Log4j 2 Performance improved against log4j 1.2 Configuration via xml, not properties file Migration tool for 1.2 to 2 available Not by original author • Disclaimer: I am the founder of log4j, slf4j and logback projects but unaffiliated with log4j 2.0. As I understand it, notwithstanding its name, log4j 2.0 is very different than log4j 1.x. As far as the user API is concerned, log4j 2.0 is largely incompatible with log4j 1.x. • stackoverflow.com/a/12095467/2581128 41KAMAL METTANANDA
  • 42. JUL - Java logging API Java itself has a logging API java.util.logging.Logger But was too late to be born 42KAMAL METTANANDA
  • 44. Learn further Logback Log4j 2 JUL - Java logging API Commons-logging SLF4j 44KAMAL METTANANDA