SlideShare a Scribd company logo
Functional Logging in
Spring Boot App
Presented By Sabir Khan
Agenda
 Functional Logging - Need
 Logging- General Overview
 Spring Boot Logging
 Start Functional Logging
 Conclusion
 References
 Thanks
Functional Logging - Need
• What I am calling functional logging is segregation of application logs based on
component functionality and not based on individual class names
• E.g. If an application can be functionally divided into two components – lets say
Indexer and Searcher then all classes that belong to Indexer should write to one log
file and all classes that belong to searcher should write to another log file
• Another example could be a system having multiple REST End points – you log based
on REST URLs and not for specific implementation classes i.e. service1 logs are
located on file1 , service2 on file2 and so on
• This simplifies production support and debugging to a great deal and makes product
easily supportable
• All classes writing to one single file and intermingling of all logs in one file is the worst
form of logging that I saw as far as production support and debugging is concerned
Functional Logging - Need
• So all in all, you are logging for a functional flow and not for individual classes and you
are not logging to a single file but scattered over multiple files
• E.g. If I have to check an Indexer issue, You will check only Indexer logs which will be
according to Indexer functional flow
• So a group of classes belonging to a particular application function flow will write to
one file and second flow will write to second and so on
• Application flow segregation should be accurate and should not be too refined or too
bulky – there has to be a balance
• Log files for an application flow will rotate as per configured log size
• Developers will have to just stop using class name as logger entity and start using a
provided logger name as logged entity for a group of classes
Logging- General Overview
• Logging in Java has been made over complicated due to over engineering
• Complications arose because there were many logging implementations coming out
• Architects and Developers were willing to try various logging APIs for various features
and performance reasons but wanted their code to be neutral to logging API change
• So there comes first level logging façade design pattern like – SLF4j (Simple Logging
Facade for Java ). I call it LEVEL-1 of abstraction with actual implementation being
LEVEL-0
• LEVEL – 0 i.e. actual implementations generally are – java.util.logging , logback and
log4j
• There are LEVEL-2 frameworks too i.e. FAÇADE of FAÇADE and I usually find them
not very useful
Logging- General Overview
• Most of applications will do just fine even with LEVEL - 0 but its better to be on
LEVEL-1 so you can change your LEVEL- 0s whenever you want if something better
comes in market
• In this presentation, I will be using SLF4j as FAÇADE and logback as implementation
• SLF4j is not an implementation of logging, its simply a façade for actual logging
implementations to simplify logging subsystems
• Another popular FAÇADE is Apache Commons Logging API
Spring Boot Logging
• Spring Boot starter POM for Web – App ( i.e. spring-boot-starter-web) already
includes spring-boot-starter-logging as dependency so you wouldn’t need any extra
dependency
• Spring Boot has a LoggingSystem abstraction that attempts to configure logging
based on contents fo classpath, giving first preference to Logback
• So for your spring-boot-starter-web application, you will get – logback-classic-*.jar,
logback-core-*.jar , jul-to-slf4j-*.jar , log4j-over-slf4j-*.jar , jcl-over-slf4j-*.jar, slf4j-api-
*.jar etc in your application
• Further Logging Levels etc can be configured using application.properties file by using
, properties like - logging.level….= ,
Start Functional Logging
• First, in your application – create a xml files, lets say logging.xml which will more or less look like
below and put it under src/main/resources
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml" />
<property name="LOG_PATH" value="/var/logs" />
<appender name="Console-Appender" class="ch.qos.logback.core.ConsoleAppender">
<layout>
<pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n
</pattern>
</layout>
</appender>
Start Functional Logging…Contd
<appender name=“Function1Logs"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_PATH}/ Function1Logs.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<fileNamePattern>${LOG_PATH}/Function1Logs.%i.log
</fileNamePattern>
<minIndex>1</minIndex>
<maxIndex>600</maxIndex>
</rollingPolicy>
<triggeringPolicy
class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>5MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n
</pattern>
<outputPatternAsHeader>true</outputPatternAsHeader>
</encoder>
</appender>
Start Functional Logging…Contd
<logger name="Function1Logger" level="debug" additivity="false">
<appender-ref ref=" Function1Logs " />
</logger>
<root> <appender-ref ref="Console-Appender" /> </root>
</configuration>
-
The important thing to note in above XML is definition of logger name -
Function1Logger and that referring to - Function1Logs appender that has actual
appender configuration
Start Functional Logging…Contd
- Spring Boot will automatically read your XML but if not , you can say in
application.properties that - logging.config=classpath:logging.xml
- Now at Java code level, class - org.slf4j.LoggerFactory has two getLogger(…)
methods,
public static Logger getLogger(String name) & public static Logger
getLogger(Class<?> clazz)
It’s the first version - getLogger(String name) string that helps in achieving functional
logging.
Start Functional Logging…Contd
- In your Java class, you should do ,
private static final Logger logger = LoggerFactory.getLogger(“Function1Logger”);
Instead of the one with class name.
- Now at all classes, that form one flow of application function, you should use above
logger name to get Logger and use that for your logging.
- Group your application classes in appropriate number flows and add entries on
logging.xml for all such loggers and use those logger names in getting Logger
instances in your Java classes
Conclusion
- This way your logs will not be HOTCH – POTCH in one big log file or log files for
each class without connecting the classes functionally
- Developer has to still make an effort to know which logger his current class belongs
to
- So for your application, with lets say 100 classes will have like 4 -5 functionally
independent logs. Without specific logger names for each function, you either have
one log file for each class or one file for all the classes
- In non – Spring Boot Systems, you will have to just make arrangement to load that
XML file to memory in some way and add explicit dependencies manually
References
1. https://docs.spring.io/spring-boot/docs/current/reference/html/howto-logging.html
2. http://stackoverflow.com/questions/3825276/whats-the-point-of-a-logging-facade
3. https://sourcemaking.com/design_patterns/facade
4. https://www.slf4j.org/manual.html
Thank You !!
Thank You !!
Ad

More Related Content

What's hot (20)

Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
Dzmitry Naskou
 
Spring boot
Spring bootSpring boot
Spring boot
Pradeep Shanmugam
 
Spring Core
Spring CoreSpring Core
Spring Core
Pushan Bhattacharya
 
Swagger With REST APIs.pptx.pdf
Swagger With REST APIs.pptx.pdfSwagger With REST APIs.pptx.pdf
Swagger With REST APIs.pptx.pdf
Knoldus Inc.
 
Angular
AngularAngular
Angular
TejinderMakkar
 
Postman
PostmanPostman
Postman
Igor Shubovych
 
core java
core javacore java
core java
Roushan Sinha
 
Spring ppt
Spring pptSpring ppt
Spring ppt
Mumbai Academisc
 
Selenium-Locators
Selenium-LocatorsSelenium-Locators
Selenium-Locators
Mithilesh Singh
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
Alex Movila
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
NexThoughts Technologies
 
Swagger UI
Swagger UISwagger UI
Swagger UI
Walaa Hamdy Assy
 
Java Logging
Java LoggingJava Logging
Java Logging
Zeeshan Bilal
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Jaran Flaath
 
Spring boot
Spring bootSpring boot
Spring boot
Gyanendra Yadav
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
07.pallav
 
Spring core module
Spring core moduleSpring core module
Spring core module
Raj Tomar
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...
Mr. Akaash
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
AnushaNaidu
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)
Sujit Majety
 

Similar to Functional Application Logging : Code Examples Using Spring Boot and Logback (20)

Log4e
Log4eLog4e
Log4e
Gagandeep Singh
 
Logging best practice in mule using logger component
Logging best practice in mule using logger componentLogging best practice in mule using logger component
Logging best practice in mule using logger component
Govind Mulinti
 
Logging configuration in mule
Logging configuration in muleLogging configuration in mule
Logging configuration in mule
Son Nguyen
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and Bytecode
Yoav Avrahami
 
Logging
LoggingLogging
Logging
Марія Русин
 
Log4e
Log4eLog4e
Log4e
husnara mohammad
 
AtoM feature development
AtoM feature developmentAtoM feature development
AtoM feature development
Artefactual Systems - AtoM
 
Domino java
Domino javaDomino java
Domino java
Sumit Tambe
 
Lecture11_LaravelGetStarted_SPring2023.pdf
Lecture11_LaravelGetStarted_SPring2023.pdfLecture11_LaravelGetStarted_SPring2023.pdf
Lecture11_LaravelGetStarted_SPring2023.pdf
ShaimaaMohamedGalal
 
Javantura v4 - FreeMarker in Spring web - Marin Kalapać
Javantura v4 - FreeMarker in Spring web - Marin KalapaćJavantura v4 - FreeMarker in Spring web - Marin Kalapać
Javantura v4 - FreeMarker in Spring web - Marin Kalapać
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
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
 
Java logging
Java loggingJava logging
Java logging
Jumping Bean
 
Logger
LoggerLogger
Logger
Srilatha Kante
 
Logging from the bottom up
Logging from the bottom upLogging from the bottom up
Logging from the bottom up
Francis Edwards
 
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
Johannes Fischer
 
Mule debugging logging_configuration_in_mule
Mule debugging logging_configuration_in_muleMule debugging logging_configuration_in_mule
Mule debugging logging_configuration_in_mule
kunal vishe
 
Enhanced Reframework Session_16-07-2022.pptx
Enhanced Reframework Session_16-07-2022.pptxEnhanced Reframework Session_16-07-2022.pptx
Enhanced Reframework Session_16-07-2022.pptx
Rohit Radhakrishnan
 
Milano Meetups #15 - Log Forwarding.pptx.pdf
Milano Meetups #15 - Log Forwarding.pptx.pdfMilano Meetups #15 - Log Forwarding.pptx.pdf
Milano Meetups #15 - Log Forwarding.pptx.pdf
Florence Consulting
 
SLF4J Explained........
SLF4J Explained........SLF4J Explained........
SLF4J Explained........
Sunitha Satyadas
 
Spring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsSpring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applications
michaelaaron25322
 
Logging best practice in mule using logger component
Logging best practice in mule using logger componentLogging best practice in mule using logger component
Logging best practice in mule using logger component
Govind Mulinti
 
Logging configuration in mule
Logging configuration in muleLogging configuration in mule
Logging configuration in mule
Son Nguyen
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and Bytecode
Yoav Avrahami
 
Lecture11_LaravelGetStarted_SPring2023.pdf
Lecture11_LaravelGetStarted_SPring2023.pdfLecture11_LaravelGetStarted_SPring2023.pdf
Lecture11_LaravelGetStarted_SPring2023.pdf
ShaimaaMohamedGalal
 
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
 
Logging from the bottom up
Logging from the bottom upLogging from the bottom up
Logging from the bottom up
Francis Edwards
 
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
Johannes Fischer
 
Mule debugging logging_configuration_in_mule
Mule debugging logging_configuration_in_muleMule debugging logging_configuration_in_mule
Mule debugging logging_configuration_in_mule
kunal vishe
 
Enhanced Reframework Session_16-07-2022.pptx
Enhanced Reframework Session_16-07-2022.pptxEnhanced Reframework Session_16-07-2022.pptx
Enhanced Reframework Session_16-07-2022.pptx
Rohit Radhakrishnan
 
Milano Meetups #15 - Log Forwarding.pptx.pdf
Milano Meetups #15 - Log Forwarding.pptx.pdfMilano Meetups #15 - Log Forwarding.pptx.pdf
Milano Meetups #15 - Log Forwarding.pptx.pdf
Florence Consulting
 
Spring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsSpring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applications
michaelaaron25322
 
Ad

Recently uploaded (20)

Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
BookNet Canada
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
The Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdfThe Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdf
Precisely
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
AI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of DocumentsAI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of Documents
UiPathCommunity
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptxWebinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
MSP360
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Make GenAI investments go further with the Dell AI Factory
Make GenAI investments go further with the Dell AI FactoryMake GenAI investments go further with the Dell AI Factory
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Play It Safe: Manage Security Risks - Google Certificate
Play It Safe: Manage Security Risks - Google CertificatePlay It Safe: Manage Security Risks - Google Certificate
Play It Safe: Manage Security Risks - Google Certificate
VICTOR MAESTRE RAMIREZ
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
BookNet Canada
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
The Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdfThe Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdf
Precisely
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
AI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of DocumentsAI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of Documents
UiPathCommunity
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptxWebinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
MSP360
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
Make GenAI investments go further with the Dell AI Factory
Make GenAI investments go further with the Dell AI FactoryMake GenAI investments go further with the Dell AI Factory
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Play It Safe: Manage Security Risks - Google Certificate
Play It Safe: Manage Security Risks - Google CertificatePlay It Safe: Manage Security Risks - Google Certificate
Play It Safe: Manage Security Risks - Google Certificate
VICTOR MAESTRE RAMIREZ
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
Ad

Functional Application Logging : Code Examples Using Spring Boot and Logback

  • 1. Functional Logging in Spring Boot App Presented By Sabir Khan
  • 2. Agenda  Functional Logging - Need  Logging- General Overview  Spring Boot Logging  Start Functional Logging  Conclusion  References  Thanks
  • 3. Functional Logging - Need • What I am calling functional logging is segregation of application logs based on component functionality and not based on individual class names • E.g. If an application can be functionally divided into two components – lets say Indexer and Searcher then all classes that belong to Indexer should write to one log file and all classes that belong to searcher should write to another log file • Another example could be a system having multiple REST End points – you log based on REST URLs and not for specific implementation classes i.e. service1 logs are located on file1 , service2 on file2 and so on • This simplifies production support and debugging to a great deal and makes product easily supportable • All classes writing to one single file and intermingling of all logs in one file is the worst form of logging that I saw as far as production support and debugging is concerned
  • 4. Functional Logging - Need • So all in all, you are logging for a functional flow and not for individual classes and you are not logging to a single file but scattered over multiple files • E.g. If I have to check an Indexer issue, You will check only Indexer logs which will be according to Indexer functional flow • So a group of classes belonging to a particular application function flow will write to one file and second flow will write to second and so on • Application flow segregation should be accurate and should not be too refined or too bulky – there has to be a balance • Log files for an application flow will rotate as per configured log size • Developers will have to just stop using class name as logger entity and start using a provided logger name as logged entity for a group of classes
  • 5. Logging- General Overview • Logging in Java has been made over complicated due to over engineering • Complications arose because there were many logging implementations coming out • Architects and Developers were willing to try various logging APIs for various features and performance reasons but wanted their code to be neutral to logging API change • So there comes first level logging façade design pattern like – SLF4j (Simple Logging Facade for Java ). I call it LEVEL-1 of abstraction with actual implementation being LEVEL-0 • LEVEL – 0 i.e. actual implementations generally are – java.util.logging , logback and log4j • There are LEVEL-2 frameworks too i.e. FAÇADE of FAÇADE and I usually find them not very useful
  • 6. Logging- General Overview • Most of applications will do just fine even with LEVEL - 0 but its better to be on LEVEL-1 so you can change your LEVEL- 0s whenever you want if something better comes in market • In this presentation, I will be using SLF4j as FAÇADE and logback as implementation • SLF4j is not an implementation of logging, its simply a façade for actual logging implementations to simplify logging subsystems • Another popular FAÇADE is Apache Commons Logging API
  • 7. Spring Boot Logging • Spring Boot starter POM for Web – App ( i.e. spring-boot-starter-web) already includes spring-boot-starter-logging as dependency so you wouldn’t need any extra dependency • Spring Boot has a LoggingSystem abstraction that attempts to configure logging based on contents fo classpath, giving first preference to Logback • So for your spring-boot-starter-web application, you will get – logback-classic-*.jar, logback-core-*.jar , jul-to-slf4j-*.jar , log4j-over-slf4j-*.jar , jcl-over-slf4j-*.jar, slf4j-api- *.jar etc in your application • Further Logging Levels etc can be configured using application.properties file by using , properties like - logging.level….= ,
  • 8. Start Functional Logging • First, in your application – create a xml files, lets say logging.xml which will more or less look like below and put it under src/main/resources <?xml version="1.0" encoding="UTF-8"?> <configuration> <include resource="org/springframework/boot/logging/logback/base.xml" /> <property name="LOG_PATH" value="/var/logs" /> <appender name="Console-Appender" class="ch.qos.logback.core.ConsoleAppender"> <layout> <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n </pattern> </layout> </appender>
  • 9. Start Functional Logging…Contd <appender name=“Function1Logs" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${LOG_PATH}/ Function1Logs.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> <fileNamePattern>${LOG_PATH}/Function1Logs.%i.log </fileNamePattern> <minIndex>1</minIndex> <maxIndex>600</maxIndex> </rollingPolicy> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <maxFileSize>5MB</maxFileSize> </triggeringPolicy> <encoder> <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n </pattern> <outputPatternAsHeader>true</outputPatternAsHeader> </encoder> </appender>
  • 10. Start Functional Logging…Contd <logger name="Function1Logger" level="debug" additivity="false"> <appender-ref ref=" Function1Logs " /> </logger> <root> <appender-ref ref="Console-Appender" /> </root> </configuration> - The important thing to note in above XML is definition of logger name - Function1Logger and that referring to - Function1Logs appender that has actual appender configuration
  • 11. Start Functional Logging…Contd - Spring Boot will automatically read your XML but if not , you can say in application.properties that - logging.config=classpath:logging.xml - Now at Java code level, class - org.slf4j.LoggerFactory has two getLogger(…) methods, public static Logger getLogger(String name) & public static Logger getLogger(Class<?> clazz) It’s the first version - getLogger(String name) string that helps in achieving functional logging.
  • 12. Start Functional Logging…Contd - In your Java class, you should do , private static final Logger logger = LoggerFactory.getLogger(“Function1Logger”); Instead of the one with class name. - Now at all classes, that form one flow of application function, you should use above logger name to get Logger and use that for your logging. - Group your application classes in appropriate number flows and add entries on logging.xml for all such loggers and use those logger names in getting Logger instances in your Java classes
  • 13. Conclusion - This way your logs will not be HOTCH – POTCH in one big log file or log files for each class without connecting the classes functionally - Developer has to still make an effort to know which logger his current class belongs to - So for your application, with lets say 100 classes will have like 4 -5 functionally independent logs. Without specific logger names for each function, you either have one log file for each class or one file for all the classes - In non – Spring Boot Systems, you will have to just make arrangement to load that XML file to memory in some way and add explicit dependencies manually

Editor's Notes

  • #2: NOTE: To change the image on this slide, select the picture and delete it. Then click the Pictures icon in the placeholder to insert your own image.