SlideShare a Scribd company logo
1 of 17
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
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

Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksSamundra khatri
 
Functional Application Logging : Code Examples Using Spring Boot and Logback
Functional Application Logging : Code Examples Using Spring Boot and LogbackFunctional Application Logging : Code Examples Using Spring Boot and Logback
Functional Application Logging : Code Examples Using Spring Boot and LogbackMohammad Sabir Khan
 
java 8 new features
java 8 new features java 8 new features
java 8 new features Rohit Verma
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpaStaples
 
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016Christian Schneider
 
React js programming concept
React js programming conceptReact js programming concept
React js programming conceptTariqul islam
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features OverviewSergii Stets
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesSteven Smith
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate pptAneega
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]GDSC UofT Mississauga
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web APIBrad Genereaux
 
Networking in Java with NIO and Netty
Networking in Java with NIO and NettyNetworking in Java with NIO and Netty
Networking in Java with NIO and NettyConstantine Slisenka
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency InjectionTheo Jungeblut
 

What's hot (20)

Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Functional Application Logging : Code Examples Using Spring Boot and Logback
Functional Application Logging : Code Examples Using Spring Boot and LogbackFunctional Application Logging : Code Examples Using Spring Boot and Logback
Functional Application Logging : Code Examples Using Spring Boot and Logback
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Java data types
Java data typesJava data types
Java data types
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpa
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
Surviving the Java Deserialization Apocalypse // OWASP AppSecEU 2016
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Refactoring Applications using SOLID Principles
Refactoring Applications using SOLID PrinciplesRefactoring Applications using SOLID Principles
Refactoring Applications using SOLID Principles
 
File handling
File handlingFile handling
File handling
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
 
Networking in Java with NIO and Netty
Networking in Java with NIO and NettyNetworking in Java with NIO and Netty
Networking in Java with NIO and Netty
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency Injection
 

Similar to Java Logging

Oracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningOracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningMichel Schildmeijer
 
Logging and Exception
Logging and ExceptionLogging and Exception
Logging and ExceptionAzeem Mumtaz
 
Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test toolsAllan Huang
 
Infinum Android Talks #14 - Log4j
Infinum Android Talks #14 - Log4jInfinum Android Talks #14 - Log4j
Infinum Android Talks #14 - Log4jInfinum
 
Cashing in on logging and exception data
Cashing in on logging and exception dataCashing in on logging and exception data
Cashing in on logging and exception dataStackify
 
Conditional Logging Considered Harmful - Sean Reilly
Conditional Logging Considered Harmful - Sean ReillyConditional Logging Considered Harmful - Sean Reilly
Conditional Logging Considered Harmful - Sean ReillyJAXLondon2014
 
State of the art logging
State of the art loggingState of the art logging
State of the art loggingMilan Vukoje
 
Discover a lightning fast way to debug in Salesforce with RFLIB - Summer 20
Discover a lightning fast way to debug in Salesforce with RFLIB - Summer 20Discover a lightning fast way to debug in Salesforce with RFLIB - Summer 20
Discover a lightning fast way to debug in Salesforce with RFLIB - Summer 20Johannes Fischer
 
Integrating SLF4J and the new OSGi LogService 1.4 - BJ Hargrave (IBM)
Integrating SLF4J and the new OSGi LogService 1.4 - BJ Hargrave (IBM)Integrating SLF4J and the new OSGi LogService 1.4 - BJ Hargrave (IBM)
Integrating SLF4J and the new OSGi LogService 1.4 - BJ Hargrave (IBM)mfrancis
 
The new OSGi LogService 1.4 and integrating with SLF4J
The new OSGi LogService 1.4 and integrating with SLF4JThe new OSGi LogService 1.4 and integrating with SLF4J
The new OSGi LogService 1.4 and integrating with SLF4Jbjhargrave
 
Log4j with selenium tutorial: How to Setup log4j logging in selenium automati...
Log4j with selenium tutorial: How to Setup log4j logging in selenium automati...Log4j with selenium tutorial: How to Setup log4j logging in selenium automati...
Log4j with selenium tutorial: How to Setup log4j logging in selenium automati...Chirag Thumar
 
Oracle ADF Architecture TV - Development - Logging
Oracle ADF Architecture TV - Development - LoggingOracle ADF Architecture TV - Development - Logging
Oracle ADF Architecture TV - Development - LoggingChris Muir
 

Similar to Java Logging (20)

Log4e
Log4eLog4e
Log4e
 
Oracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuningOracle WebLogic Diagnostics & Perfomance tuning
Oracle WebLogic Diagnostics & Perfomance tuning
 
Logging and Exception
Logging and ExceptionLogging and Exception
Logging and Exception
 
Log4e
Log4eLog4e
Log4e
 
Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test tools
 
Infinum Android Talks #14 - Log4j
Infinum Android Talks #14 - Log4jInfinum Android Talks #14 - Log4j
Infinum Android Talks #14 - Log4j
 
Logging
LoggingLogging
Logging
 
Cashing in on logging and exception data
Cashing in on logging and exception dataCashing in on logging and exception data
Cashing in on logging and exception data
 
Logging with log4j v1.2
Logging with log4j v1.2Logging with log4j v1.2
Logging with log4j v1.2
 
Conditional Logging Considered Harmful - Sean Reilly
Conditional Logging Considered Harmful - Sean ReillyConditional Logging Considered Harmful - Sean Reilly
Conditional Logging Considered Harmful - Sean Reilly
 
Automation using ibm rft
Automation using ibm rftAutomation using ibm rft
Automation using ibm rft
 
FireBug And FirePHP
FireBug And FirePHPFireBug And FirePHP
FireBug And FirePHP
 
Next-gen Automation Framework
Next-gen Automation FrameworkNext-gen Automation Framework
Next-gen Automation Framework
 
State of the art logging
State of the art loggingState of the art logging
State of the art logging
 
Discover a lightning fast way to debug in Salesforce with RFLIB - Summer 20
Discover a lightning fast way to debug in Salesforce with RFLIB - Summer 20Discover a lightning fast way to debug in Salesforce with RFLIB - Summer 20
Discover a lightning fast way to debug in Salesforce with RFLIB - Summer 20
 
Integrating SLF4J and the new OSGi LogService 1.4 - BJ Hargrave (IBM)
Integrating SLF4J and the new OSGi LogService 1.4 - BJ Hargrave (IBM)Integrating SLF4J and the new OSGi LogService 1.4 - BJ Hargrave (IBM)
Integrating SLF4J and the new OSGi LogService 1.4 - BJ Hargrave (IBM)
 
The new OSGi LogService 1.4 and integrating with SLF4J
The new OSGi LogService 1.4 and integrating with SLF4JThe new OSGi LogService 1.4 and integrating with SLF4J
The new OSGi LogService 1.4 and integrating with SLF4J
 
Log4j with selenium tutorial: How to Setup log4j logging in selenium automati...
Log4j with selenium tutorial: How to Setup log4j logging in selenium automati...Log4j with selenium tutorial: How to Setup log4j logging in selenium automati...
Log4j with selenium tutorial: How to Setup log4j logging in selenium automati...
 
Selenium Training in Chennai
Selenium Training in ChennaiSelenium Training in Chennai
Selenium Training in Chennai
 
Oracle ADF Architecture TV - Development - Logging
Oracle ADF Architecture TV - Development - LoggingOracle ADF Architecture TV - Development - Logging
Oracle ADF Architecture TV - Development - Logging
 

Recently uploaded

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 

Recently uploaded (20)

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 

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
  • 12.
  • 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