SlideShare a Scribd company logo
4
Most read
5
Most read
LOGGING
AGENDA
• Why we need logging
• What is a logging framework
• What are different logging level
• How to choose correct logging level
• How logging affects performance
• Which framework to use
WHY WE NEED LOGGING
• Logging is a basic need when you create software
• Some logging use-cases are:
• debugging the software during development
• help diagnose bugs during production
• trace access for security purposes
• create data for statistical use
• etc.
• Whatever the use, logs should be
• detailed
• configurable
• Reliable
• Logging is not by choice it’s must to understand
HISTORY
• Historically, Java logs where done with
• Debug logs where put in System.out.println()
• error logs in System.err.println()
• e.printStackTrace()
• In Production, both were redirected:
• System.out on the null output,
• System.err to the desired error log file.
• Useful enough but they suffered from big drawbacks
• they were not very configurable - all or nothing switch
• could not focus detailed logs on a particular layer or package
WHAT IS A LOGGING FRAMEWORK
A logging framework is layered and consists of three main components
• Logger
• the most essential component of the logging process
• responsible for capturing the logging information
• 5 different log levels of the Logger
• Handler/Appender
• responsible for publishing the log to a destination
• Formator/Layout
• responsible for formatting the log output in different layouts
WHAT ARE DIFFERENT LOGGING LEVEL
• DEBUG
• lowest restricted logging level
• write everything we need to debug an application
• should only be used on Development and Testing
• must not be used in production
• INFO
• more restricted than DEBUG
• informative purpose like
• Server has been started
• Incoming messages
• outgoing messages
WHAT ARE DIFFERENT LOGGING LEVEL(2)
• WARN
• more restricted than INFO
• used to log warning sort of messages
• Connection lost between client and server.
• Database connection lost
• Socket reaching to its limit
• let support team monitor health of application and react on this messages
• ERROR
• more restricted logging level than WARN
• used to log Errors and Exception
• ERROR is serious for logging in Java and you should always print
HOW LOGGING AFFECTS PERFORMANCE
• More you log, more you perform file IO which slows down your application.
• Choose correct logging level for every single message is quite important.
• Since having no logging is not a choice
• What you can control is
• logging level
• logging messages on that level
• Always log DEBUG messages inside isDebugEnabled() block
• Never use DEBUG level logging in java in production
WHICH FRAMEWORK TO USE
• Log4J would be the framework of choice
• But it is no longer developed
• Version 1.2 is the reference, 1.3 is abandoned
• version 2.0 is still in its early stage
• Commons Logging is a good choice for a library (as opposed to an application)
• but I suffered once classloaders issues, and once is enough to veto it (finally, i threw
Commons Logging out and used Log4J directly)
• JDK 1.4 Logging is a standard and does not raise concurrent versions problems.
• But it lacks so many features
• it cannot be used without redeveloping
• Too bad… but it does not answers the question: which framework to use?
CUSTOM ABSTRACTION
Core
interfaces
base-
impl
log4j-
impl
jdk-impl
• LoggerFactory
• AbstractFactor
y
• Logger
• Binder • Binder
• Log4jFactory
• Logj4Logger
• Binder
• JdkFactory
• JdkLogger
Looks for Binder to get the
instance of
AbstractFactory impl and
returns concrete logger
Empty binder for
compile time use
only
Provide the
instance of
AbstractFactory
impl
(Log4jFactory)
Provide the
instance of
AbstractFactory
impl
(Log4jFactory)
SLF4J
• Simple Logging Façade for Java
• Abstract layer for logging APIs
• Completely independent of the logging implementation
• Manually/statically select underlying logging framework
• Easily to change the logging implementation without modifying the
existing code
• Only have to change the configuration of the implementation
Java Logging
PARAMETERIZED LOGGING
• Inefficient style
log.debug("Hello "+name);
• Old style:
if(log.isDebugEnabled()) {
log.debug("Hello "+name);
}
• New style:
log.debug("Hello {}", name);
THE API
1: import org.slf4j.Logger;
2: import org.slf4j.LoggerFactory;
3:
4: public class NumTag extends Tag {
5:
6: private static final Logger log = LoggerFactory.getLogger(NumTag.class);
7:
8: private Integer value;
9:
10: public void setCV(Integer newValue) {
11:
12: Integer oldValue = value;
13: value = newValue;
14:
15: log.debug("Tag CV set to {}. Old CV was {}.", newValue, oldValue);
16:
17: if(newValue.intValue() > 50) {
18: log.info("CV has risses above 50.");
19: }
20: }
21: }
USING API
• Every class should have a class level log instance
private static final Logger log =
LoggerFactory.getLogger(NumTag.class);
• Abstract Class provides an object level log instance
protected final Logger log = LoggerFactory.getLogger(getClass());
• Always use proper logging method to log relevant message
log.trace(); // general logging messages
log.debug(); // development or testing level logging
log.info(); // information like service start/load/stop, incoming
req.
log.warn(); // warnings like time out, connection lost, limit reached
log.error(); // exceptions, failures, errors
THE CONFIGURATION
1. <?xml version="1.0" encoding="UTF-8"?>
2. <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
3. <log4j:configuration>
4. <!-- log all messages to a separate log file -->
5. <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
6. <param name="file" value="product.log" />
7. <param name="maxFileSize" value="100MB" />
8. <param name="maxBackupIndex" value="10" />
9. <layout class="org.apache.log4j.PatternLayout">
10. <param name="ConversionPattern" value="%d{yyyy/MM/dd HH:mm:ss,SSS} [%t] %-5p %c %x - %m%n"/>
11. </layout>
12. </appender>
13.
14. <root>
15. <priority value="debug"></priority>
16. <appender-ref ref=" fileAppender "/>
17. </root>
18. </log4j:configuration>
BEST PRACTICES
• Use parameterized version of various log methods, they are faster as
compared to normal method.
• Carefully choose which kind of message should go to which level for
logging (If you log too much information your performance will be
affected)
• I would recommend log4j watchdog, it continuously look for
configuration in a particular directory
• Carefully choose format of logging at logger level
• Don’t forget to include Thread Name and fully qualified Class Name
while printing logs
• Both no logging and excessive logging is bad

More Related Content

What's hot (20)

PPTX
Exception handling in java
Elizabeth alexander
 
PPT
10 Creating Triggers
rehaniltifat
 
PDF
PUC SE Day 2019 - SpringBoot
Josué Neis
 
PPTX
Spring Boot
Jiayun Zhou
 
PPTX
This keyword in java
Hitesh Kumar
 
PPTX
Functional programming with Java 8
LivePerson
 
PPTX
Interfaces in java
Abishek Purushothaman
 
PPTX
Java method
sunilchute1
 
PDF
JUnit 5
Scott Leberknight
 
PDF
TypeScript Introduction
Dmitry Sheiko
 
PPTX
Exception handling in Java
Ankit Rai
 
PPTX
Exceptions in Java
Vadym Lotar
 
ODP
Java 9/10/11 - What's new and why you should upgrade
Simone Bordet
 
PPT
Exception Handling in JAVA
SURIT DATTA
 
PDF
Introduction to Java 11
Knoldus Inc.
 
PPT
Reflection in C Sharp
Harman Bajwa
 
PPTX
C# File IO Operations
Prem Kumar Badri
 
PPTX
Spring boot
sdeeg
 
PPTX
Lombok
Amit Aggarwal
 
Exception handling in java
Elizabeth alexander
 
10 Creating Triggers
rehaniltifat
 
PUC SE Day 2019 - SpringBoot
Josué Neis
 
Spring Boot
Jiayun Zhou
 
This keyword in java
Hitesh Kumar
 
Functional programming with Java 8
LivePerson
 
Interfaces in java
Abishek Purushothaman
 
Java method
sunilchute1
 
TypeScript Introduction
Dmitry Sheiko
 
Exception handling in Java
Ankit Rai
 
Exceptions in Java
Vadym Lotar
 
Java 9/10/11 - What's new and why you should upgrade
Simone Bordet
 
Exception Handling in JAVA
SURIT DATTA
 
Introduction to Java 11
Knoldus Inc.
 
Reflection in C Sharp
Harman Bajwa
 
C# File IO Operations
Prem Kumar Badri
 
Spring boot
sdeeg
 

Similar to Java Logging (20)

PPT
Logback
Anubhav Shukla
 
PDF
Java Logging discussion Log4j,Slf4j
Rajiv Gupta
 
PPT
Log4e
Gagandeep Singh
 
PDF
Log4j2
joergreichert
 
DOCX
JAVA LOGGING for JAVA APPLICATION PERFORMANCE
Rajendra Ladkat
 
PPTX
Functional and non functional application logging
Sander De Vos
 
PDF
Developer Fundamentals - Logging
Axel Irriger
 
ODP
Logging with Logback in Scala
Knoldus Inc.
 
PPTX
Build, logging, and unit test tools
Allan Huang
 
DOC
Log4j
vasu12
 
PPTX
Log4j is a reliable, fast and flexible
Ramakrishna kapa
 
PPTX
Logging with log4j v1.2
Kamal Mettananda
 
PPT
Log4j Logging Mechanism
Kunal Dabir
 
PDF
Log4j in 8 slides
Tarin Gamberini
 
PDF
Helpful logging with Java
roskakori
 
PPTX
Proper application logging
Vidula Hasaranga
 
PPTX
Logging and Exception
Azeem Mumtaz
 
PPT
Logging with Logback in Scala
Knoldus Inc.
 
Java Logging discussion Log4j,Slf4j
Rajiv Gupta
 
JAVA LOGGING for JAVA APPLICATION PERFORMANCE
Rajendra Ladkat
 
Functional and non functional application logging
Sander De Vos
 
Developer Fundamentals - Logging
Axel Irriger
 
Logging with Logback in Scala
Knoldus Inc.
 
Build, logging, and unit test tools
Allan Huang
 
Log4j
vasu12
 
Log4j is a reliable, fast and flexible
Ramakrishna kapa
 
Logging with log4j v1.2
Kamal Mettananda
 
Log4j Logging Mechanism
Kunal Dabir
 
Log4j in 8 slides
Tarin Gamberini
 
Helpful logging with Java
roskakori
 
Proper application logging
Vidula Hasaranga
 
Logging and Exception
Azeem Mumtaz
 
Logging with Logback in Scala
Knoldus Inc.
 
Ad

Recently uploaded (20)

PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
July Patch Tuesday
Ivanti
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
July Patch Tuesday
Ivanti
 
Ad

Java Logging

  • 2. AGENDA • Why we need logging • What is a logging framework • What are different logging level • How to choose correct logging level • How logging affects performance • Which framework to use
  • 3. WHY WE NEED LOGGING • Logging is a basic need when you create software • Some logging use-cases are: • debugging the software during development • help diagnose bugs during production • trace access for security purposes • create data for statistical use • etc. • Whatever the use, logs should be • detailed • configurable • Reliable • Logging is not by choice it’s must to understand
  • 4. HISTORY • Historically, Java logs where done with • Debug logs where put in System.out.println() • error logs in System.err.println() • e.printStackTrace() • In Production, both were redirected: • System.out on the null output, • System.err to the desired error log file. • Useful enough but they suffered from big drawbacks • they were not very configurable - all or nothing switch • could not focus detailed logs on a particular layer or package
  • 5. WHAT IS A LOGGING FRAMEWORK A logging framework is layered and consists of three main components • Logger • the most essential component of the logging process • responsible for capturing the logging information • 5 different log levels of the Logger • Handler/Appender • responsible for publishing the log to a destination • Formator/Layout • responsible for formatting the log output in different layouts
  • 6. WHAT ARE DIFFERENT LOGGING LEVEL • DEBUG • lowest restricted logging level • write everything we need to debug an application • should only be used on Development and Testing • must not be used in production • INFO • more restricted than DEBUG • informative purpose like • Server has been started • Incoming messages • outgoing messages
  • 7. WHAT ARE DIFFERENT LOGGING LEVEL(2) • WARN • more restricted than INFO • used to log warning sort of messages • Connection lost between client and server. • Database connection lost • Socket reaching to its limit • let support team monitor health of application and react on this messages • ERROR • more restricted logging level than WARN • used to log Errors and Exception • ERROR is serious for logging in Java and you should always print
  • 8. HOW LOGGING AFFECTS PERFORMANCE • More you log, more you perform file IO which slows down your application. • Choose correct logging level for every single message is quite important. • Since having no logging is not a choice • What you can control is • logging level • logging messages on that level • Always log DEBUG messages inside isDebugEnabled() block • Never use DEBUG level logging in java in production
  • 9. WHICH FRAMEWORK TO USE • Log4J would be the framework of choice • But it is no longer developed • Version 1.2 is the reference, 1.3 is abandoned • version 2.0 is still in its early stage • Commons Logging is a good choice for a library (as opposed to an application) • but I suffered once classloaders issues, and once is enough to veto it (finally, i threw Commons Logging out and used Log4J directly) • JDK 1.4 Logging is a standard and does not raise concurrent versions problems. • But it lacks so many features • it cannot be used without redeveloping • Too bad… but it does not answers the question: which framework to use?
  • 10. CUSTOM ABSTRACTION Core interfaces base- impl log4j- impl jdk-impl • LoggerFactory • AbstractFactor y • Logger • Binder • Binder • Log4jFactory • Logj4Logger • Binder • JdkFactory • JdkLogger Looks for Binder to get the instance of AbstractFactory impl and returns concrete logger Empty binder for compile time use only Provide the instance of AbstractFactory impl (Log4jFactory) Provide the instance of AbstractFactory impl (Log4jFactory)
  • 11. SLF4J • Simple Logging Façade for Java • Abstract layer for logging APIs • Completely independent of the logging implementation • Manually/statically select underlying logging framework • Easily to change the logging implementation without modifying the existing code • Only have to change the configuration of the implementation
  • 13. PARAMETERIZED LOGGING • Inefficient style log.debug("Hello "+name); • Old style: if(log.isDebugEnabled()) { log.debug("Hello "+name); } • New style: log.debug("Hello {}", name);
  • 14. THE API 1: import org.slf4j.Logger; 2: import org.slf4j.LoggerFactory; 3: 4: public class NumTag extends Tag { 5: 6: private static final Logger log = LoggerFactory.getLogger(NumTag.class); 7: 8: private Integer value; 9: 10: public void setCV(Integer newValue) { 11: 12: Integer oldValue = value; 13: value = newValue; 14: 15: log.debug("Tag CV set to {}. Old CV was {}.", newValue, oldValue); 16: 17: if(newValue.intValue() > 50) { 18: log.info("CV has risses above 50."); 19: } 20: } 21: }
  • 15. USING API • Every class should have a class level log instance private static final Logger log = LoggerFactory.getLogger(NumTag.class); • Abstract Class provides an object level log instance protected final Logger log = LoggerFactory.getLogger(getClass()); • Always use proper logging method to log relevant message log.trace(); // general logging messages log.debug(); // development or testing level logging log.info(); // information like service start/load/stop, incoming req. log.warn(); // warnings like time out, connection lost, limit reached log.error(); // exceptions, failures, errors
  • 16. THE CONFIGURATION 1. <?xml version="1.0" encoding="UTF-8"?> 2. <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" > 3. <log4j:configuration> 4. <!-- log all messages to a separate log file --> 5. <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender"> 6. <param name="file" value="product.log" /> 7. <param name="maxFileSize" value="100MB" /> 8. <param name="maxBackupIndex" value="10" /> 9. <layout class="org.apache.log4j.PatternLayout"> 10. <param name="ConversionPattern" value="%d{yyyy/MM/dd HH:mm:ss,SSS} [%t] %-5p %c %x - %m%n"/> 11. </layout> 12. </appender> 13. 14. <root> 15. <priority value="debug"></priority> 16. <appender-ref ref=" fileAppender "/> 17. </root> 18. </log4j:configuration>
  • 17. BEST PRACTICES • Use parameterized version of various log methods, they are faster as compared to normal method. • Carefully choose which kind of message should go to which level for logging (If you log too much information your performance will be affected) • I would recommend log4j watchdog, it continuously look for configuration in a particular directory • Carefully choose format of logging at logger level • Don’t forget to include Thread Name and fully qualified Class Name while printing logs • Both no logging and excessive logging is bad