SlideShare una empresa de Scribd logo
1 de 17
Logging Best Practices
Afsaneh Abouei
Afsaneh.Abouei@gmail.com
Logging Best Practices
 What is Logging?
 Why Logging is important?
 What are Logging Best Practices?
Logging Best Practices
Use the appropriate tools for the job
o SLF4J : A façade for different logging tools which
can be plugged without any code change
o Advantages:
o Parameter Substitution
o No need for isDebugEnabled
o MDC (Map Diagnostic Context)
o Logback is recommended as an
implementation
Logging Best Practices
Cost of constructing the message parameter, regardless of
whether the message will be logged or not.
Avoid the cost of parameter construction
Better yet, use parameterized messages
logger.debug(“Number: " + i + " is " + String.valueOf(entry[i]));
if(logger.isDebugEnabled()) {
logger.debug(“Number: " + i + " is " +
String.valueOf(entry[i]));
}
logger.debug(“Number: {} is {}" i , String.valueOf(entry[i]));
Logging Best Practices
Get organized with named loggers
o Which component wrote a specific message
to the log
o Declare the logger both static and final to
ensure every instance of a class shares the
logger object
static final Logger logger =
LoggerService.GetLogger(“ac.components.WidgetClass");
Logging Best Practices
Choose proper logging levels
ERROR - Something terribly wrong had happened
- No system can tolerate items logged on this level
WARN - The process might be continued, but take extra caution
- Need attention
INFO - Important business process has finished
- each action that changes the state of the application
significantly
DEBUG - Developers stuff
- When can not use debugger tool
TRACE - Very detailed information, only for development but on
production
Logging Best Practices
Do you know what you are logging?
o Don’t generate NPE in log statements
o Use ‘id’ of domain objects
o Implement ‘toString()’ method for domain objects
o Use ‘Arrays#deepToString’
o And read your logs often to spot incorrectly
formatted messages
log.debug("Processing request with id: {}", request.getId());
log.debug("Returning users: {}", users);
Logging Best Practices
Avoid side effects
o Avoid log too much or improperly use toString() and/or string
concatenation
o Use SLF4J ‘Parameter Substitution’ feature
try {
log.trace("Id=" + request.getUser().getId()
+ " accesses " + manager.getPage().getUrl().toString())
} catch(NullPointerException e) {
}
Logging Best Practices
Be concise and descriptive
o Log files should be readable, clean and
descriptive
o Avoid logging everything
o Don’t use magic numbers
o Log values, numbers, ids and include their
context
o Not to log passwords and any personal
information
Logging Best Practices
Be concise and descriptive
log.debug(“Message processed”);
log.debug(msg.getJMSMessageID());
log.debug("Message with id '{}' processed",
msg.getJMSMessageID());
if(message instanceof TextMessage){
//...
}Else{
log.warn("Unknown message type");
}
Logging Best Practices
Tune your pattern
o In Logback
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppend
er">
<encoder>
<pattern>%d{HH:mm:ss.SSS} %-5level [%thread][%logger{0}]
%m%n</pattern>
</encoder>
</appender>
Logging Best Practices
Tune your pattern
o Use meaningful messages relevant to the
context
o Mapped Diagnostic Context (MDC)
2009-06-0508:15:23]INFO] User credentials entered
2009-06-0508:15:23]WARN] Incorrect PIN
2009-06-0508:15:37]INFO] User credentials entered
2009-06-0508:15:37]INFO] User credentials validated
2009-06-0508:15:46]INFO] Cash withdrawal requested
2009-06-0508:15:47]ERROR] Communication failure
Acme.ATM.Integration.ServerException: Unable to connect to bank server
...
Logging Best Practices
Log method arguments and return values
o It is always better to have too much rather
than too few logging statements
o Your code should be covered with logging
routines as it is with unit tests
o Use DEBUG or TRACE levels
Logging Best Practices
Watch out for external systems
o Log every piece of data that comes out from
your application and gets in
o Be extra careful when integrating with
external systems and prepare to pay that
cost
o Use different log levels
Logging Best Practices
Log exceptions properly
o Avoid logging exceptions
o Not all exceptions are errors
o Log OR wrap and throw back
Try {
//….
Catch (Exception e) {
log.error(“IO Exception”, e);
Throw new MyCustomException(e);
}
Logging Best Practices
Log exceptions properly
  Try {
Integer x = null;
++x;
}Catch (Exception e) {
log.error(e.toString());        //A
log.error(e.getMessage());        //B
log.error("", e); //C
log.error("{}", e.getMessage());        //D
log.error("Error reading configuration file: " + e);        //E
log.error("Error reading configuration file: " + e.getFile());       //F
log.error("Error reading configuration file ", e); //G
       Throw new MyCustomException(e);
}
Logging Best Practices
Thank You!

Más contenido relacionado

La actualidad más candente

Pascarello_Investigating JavaScript and Ajax Security
Pascarello_Investigating JavaScript and Ajax SecurityPascarello_Investigating JavaScript and Ajax Security
Pascarello_Investigating JavaScript and Ajax Securityamiable_indian
 
Exception handling
Exception handlingException handling
Exception handlingIblesoft
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!DataArt
 
Exception handling
Exception handlingException handling
Exception handlingMinal Maniar
 
jQuery : Talk to server with Ajax
jQuery : Talk to server with AjaxjQuery : Talk to server with Ajax
jQuery : Talk to server with AjaxWildan Maulana
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingHoat Le
 
"Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin "Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin Vasil Remeniuk
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureSalesforce Developers
 
Laporan tugas network programming
Laporan tugas network programmingLaporan tugas network programming
Laporan tugas network programmingRahmatHamdani2
 
Xml processing in scala
Xml processing in scalaXml processing in scala
Xml processing in scalaKnoldus Inc.
 
Exception handling
Exception handlingException handling
Exception handlingRavi Sharda
 
Manage software dependencies with ioc and aop
Manage software dependencies with ioc and aopManage software dependencies with ioc and aop
Manage software dependencies with ioc and aopStefano Leli
 
Adam Peller Interoperable Ajax Tools And Mashups
Adam Peller Interoperable Ajax Tools And MashupsAdam Peller Interoperable Ajax Tools And Mashups
Adam Peller Interoperable Ajax Tools And MashupsAjax Experience 2009
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPMCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPAli Shah
 
Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.netNeelesh Shukla
 
Exception handling
Exception handlingException handling
Exception handlingpooja kumari
 
OCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertionsOCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertionsHari kiran G
 
14 exception handling
14 exception handling14 exception handling
14 exception handlingjigeno
 

La actualidad más candente (20)

Pascarello_Investigating JavaScript and Ajax Security
Pascarello_Investigating JavaScript and Ajax SecurityPascarello_Investigating JavaScript and Ajax Security
Pascarello_Investigating JavaScript and Ajax Security
 
5 xml parsing
5   xml parsing5   xml parsing
5 xml parsing
 
Exception handling
Exception handlingException handling
Exception handling
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!
 
Exception handling
Exception handlingException handling
Exception handling
 
jQuery : Talk to server with Ajax
jQuery : Talk to server with AjaxjQuery : Talk to server with Ajax
jQuery : Talk to server with Ajax
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
"Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin "Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock Structure
 
Laporan tugas network programming
Laporan tugas network programmingLaporan tugas network programming
Laporan tugas network programming
 
Xml processing in scala
Xml processing in scalaXml processing in scala
Xml processing in scala
 
Exception handling
Exception handlingException handling
Exception handling
 
Manage software dependencies with ioc and aop
Manage software dependencies with ioc and aopManage software dependencies with ioc and aop
Manage software dependencies with ioc and aop
 
Adam Peller Interoperable Ajax Tools And Mashups
Adam Peller Interoperable Ajax Tools And MashupsAdam Peller Interoperable Ajax Tools And Mashups
Adam Peller Interoperable Ajax Tools And Mashups
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPMCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
 
Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.net
 
Exception handling
Exception handlingException handling
Exception handling
 
OCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertionsOCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertions
 
14 exception handling
14 exception handling14 exception handling
14 exception handling
 

Destacado

Splunk Application logging Best Practices
Splunk Application logging Best PracticesSplunk Application logging Best Practices
Splunk Application logging Best PracticesGreg Hanchin
 
Java Exception Handling, Assertions and Logging
Java Exception Handling, Assertions and LoggingJava Exception Handling, Assertions and Logging
Java Exception Handling, Assertions and LoggingRiccardo Cardin
 
Data logger presentation
Data logger presentationData logger presentation
Data logger presentationshidaaziri
 
Data Logging
Data LoggingData Logging
Data Loggingdjastall
 
The State of Logging on Docker
The State of Logging on DockerThe State of Logging on Docker
The State of Logging on DockerTrevor Parsons
 
Log4j Logging Mechanism
Log4j Logging MechanismLog4j Logging Mechanism
Log4j Logging MechanismKunal Dabir
 
6 Million Ways To Log In Docker - NYC Docker Meetup 12/17/2014
6 Million Ways To Log In Docker - NYC Docker Meetup 12/17/20146 Million Ways To Log In Docker - NYC Docker Meetup 12/17/2014
6 Million Ways To Log In Docker - NYC Docker Meetup 12/17/2014Christian Beedgen
 
Docker Container Security - A Network View
Docker Container Security - A Network ViewDocker Container Security - A Network View
Docker Container Security - A Network ViewNeuVector
 
Java Exception Handling Best Practices - Improved Second Version
Java Exception Handling Best Practices - Improved Second VersionJava Exception Handling Best Practices - Improved Second Version
Java Exception Handling Best Practices - Improved Second VersionLemi Orhan Ergin
 
Comprehensive Monitoring for Docker
Comprehensive Monitoring for DockerComprehensive Monitoring for Docker
Comprehensive Monitoring for DockerChristian Beedgen
 
Log Mining: Beyond Log Analysis
Log Mining: Beyond Log AnalysisLog Mining: Beyond Log Analysis
Log Mining: Beyond Log AnalysisAnton Chuvakin
 
AWS re:Invent 2016: Security Automation: Spend Less Time Securing Your Applic...
AWS re:Invent 2016: Security Automation: Spend Less Time Securing Your Applic...AWS re:Invent 2016: Security Automation: Spend Less Time Securing Your Applic...
AWS re:Invent 2016: Security Automation: Spend Less Time Securing Your Applic...Amazon Web Services
 
Powerpoint presentation for data logging
Powerpoint presentation for data loggingPowerpoint presentation for data logging
Powerpoint presentation for data loggingSufinah Ensian
 

Destacado (18)

Splunk Application logging Best Practices
Splunk Application logging Best PracticesSplunk Application logging Best Practices
Splunk Application logging Best Practices
 
Java Exception Handling, Assertions and Logging
Java Exception Handling, Assertions and LoggingJava Exception Handling, Assertions and Logging
Java Exception Handling, Assertions and Logging
 
Data logger presentation
Data logger presentationData logger presentation
Data logger presentation
 
Data Logging
Data LoggingData Logging
Data Logging
 
The State of Logging on Docker
The State of Logging on DockerThe State of Logging on Docker
The State of Logging on Docker
 
Logging & Docker - Season 2
Logging & Docker - Season 2Logging & Docker - Season 2
Logging & Docker - Season 2
 
Log4j in 8 slides
Log4j in 8 slidesLog4j in 8 slides
Log4j in 8 slides
 
Log4j Logging Mechanism
Log4j Logging MechanismLog4j Logging Mechanism
Log4j Logging Mechanism
 
Logging in Docker
Logging in DockerLogging in Docker
Logging in Docker
 
6 Million Ways To Log In Docker - NYC Docker Meetup 12/17/2014
6 Million Ways To Log In Docker - NYC Docker Meetup 12/17/20146 Million Ways To Log In Docker - NYC Docker Meetup 12/17/2014
6 Million Ways To Log In Docker - NYC Docker Meetup 12/17/2014
 
Validation
ValidationValidation
Validation
 
Docker Container Security - A Network View
Docker Container Security - A Network ViewDocker Container Security - A Network View
Docker Container Security - A Network View
 
Tibco-Exception Handling
Tibco-Exception HandlingTibco-Exception Handling
Tibco-Exception Handling
 
Java Exception Handling Best Practices - Improved Second Version
Java Exception Handling Best Practices - Improved Second VersionJava Exception Handling Best Practices - Improved Second Version
Java Exception Handling Best Practices - Improved Second Version
 
Comprehensive Monitoring for Docker
Comprehensive Monitoring for DockerComprehensive Monitoring for Docker
Comprehensive Monitoring for Docker
 
Log Mining: Beyond Log Analysis
Log Mining: Beyond Log AnalysisLog Mining: Beyond Log Analysis
Log Mining: Beyond Log Analysis
 
AWS re:Invent 2016: Security Automation: Spend Less Time Securing Your Applic...
AWS re:Invent 2016: Security Automation: Spend Less Time Securing Your Applic...AWS re:Invent 2016: Security Automation: Spend Less Time Securing Your Applic...
AWS re:Invent 2016: Security Automation: Spend Less Time Securing Your Applic...
 
Powerpoint presentation for data logging
Powerpoint presentation for data loggingPowerpoint presentation for data logging
Powerpoint presentation for data logging
 

Similar a LoggingBestPractices

Logging, Serilog, Structured Logging, Seq
Logging, Serilog, Structured Logging, SeqLogging, Serilog, Structured Logging, Seq
Logging, Serilog, Structured Logging, SeqDoruk Uluçay
 
Logging in Python for large applications
Logging in Python for large applicationsLogging in Python for large applications
Logging in Python for large applicationsFayaz Yusuf Khan
 
10 Tips to improve your application logs
10 Tips to improve your application logs10 Tips to improve your application logs
10 Tips to improve your application logsVanessa Gomes
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerSrikanth Shreenivas
 
Optimization in Programming languages
Optimization in Programming languagesOptimization in Programming languages
Optimization in Programming languagesAnkit Pandey
 
Software Engineering - RS4
Software Engineering - RS4Software Engineering - RS4
Software Engineering - RS4AtakanAral
 
HashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin InfrastructureHashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin InfrastructureNicolas Corrarello
 
Logstash-Elasticsearch-Kibana
Logstash-Elasticsearch-KibanaLogstash-Elasticsearch-Kibana
Logstash-Elasticsearch-Kibanadknx01
 
Sumo Logic "How to" Webinar: Advanced Analytics
Sumo Logic "How to" Webinar: Advanced AnalyticsSumo Logic "How to" Webinar: Advanced Analytics
Sumo Logic "How to" Webinar: Advanced AnalyticsSumo Logic
 
Java best practices
Java best practicesJava best practices
Java best practicesRay Toal
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)David McCarter
 

Similar a LoggingBestPractices (20)

Logging, Serilog, Structured Logging, Seq
Logging, Serilog, Structured Logging, SeqLogging, Serilog, Structured Logging, Seq
Logging, Serilog, Structured Logging, Seq
 
Logging in Python for large applications
Logging in Python for large applicationsLogging in Python for large applications
Logging in Python for large applications
 
Log Aggregation
Log AggregationLog Aggregation
Log Aggregation
 
Log4j
Log4jLog4j
Log4j
 
10 Tips to improve your application logs
10 Tips to improve your application logs10 Tips to improve your application logs
10 Tips to improve your application logs
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
 
Clean code
Clean codeClean code
Clean code
 
Visual Basic 6.0
Visual Basic 6.0Visual Basic 6.0
Visual Basic 6.0
 
Optimization in Programming languages
Optimization in Programming languagesOptimization in Programming languages
Optimization in Programming languages
 
Presentation log4 j
Presentation log4 jPresentation log4 j
Presentation log4 j
 
Presentation log4 j
Presentation log4 jPresentation log4 j
Presentation log4 j
 
Software Engineering - RS4
Software Engineering - RS4Software Engineering - RS4
Software Engineering - RS4
 
HashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin InfrastructureHashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin Infrastructure
 
Python for web security - beginner
Python for web security - beginnerPython for web security - beginner
Python for web security - beginner
 
Logstash-Elasticsearch-Kibana
Logstash-Elasticsearch-KibanaLogstash-Elasticsearch-Kibana
Logstash-Elasticsearch-Kibana
 
Sumo Logic "How to" Webinar: Advanced Analytics
Sumo Logic "How to" Webinar: Advanced AnalyticsSumo Logic "How to" Webinar: Advanced Analytics
Sumo Logic "How to" Webinar: Advanced Analytics
 
Java best practices
Java best practicesJava best practices
Java best practices
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 
Logs
LogsLogs
Logs
 
Unit 3
Unit 3 Unit 3
Unit 3
 

Último

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
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
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 

Último (20)

Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 

LoggingBestPractices

  • 1. Logging Best Practices Afsaneh Abouei Afsaneh.Abouei@gmail.com
  • 2. Logging Best Practices  What is Logging?  Why Logging is important?  What are Logging Best Practices?
  • 3. Logging Best Practices Use the appropriate tools for the job o SLF4J : A façade for different logging tools which can be plugged without any code change o Advantages: o Parameter Substitution o No need for isDebugEnabled o MDC (Map Diagnostic Context) o Logback is recommended as an implementation
  • 4. Logging Best Practices Cost of constructing the message parameter, regardless of whether the message will be logged or not. Avoid the cost of parameter construction Better yet, use parameterized messages logger.debug(“Number: " + i + " is " + String.valueOf(entry[i])); if(logger.isDebugEnabled()) { logger.debug(“Number: " + i + " is " + String.valueOf(entry[i])); } logger.debug(“Number: {} is {}" i , String.valueOf(entry[i]));
  • 5. Logging Best Practices Get organized with named loggers o Which component wrote a specific message to the log o Declare the logger both static and final to ensure every instance of a class shares the logger object static final Logger logger = LoggerService.GetLogger(“ac.components.WidgetClass");
  • 6. Logging Best Practices Choose proper logging levels ERROR - Something terribly wrong had happened - No system can tolerate items logged on this level WARN - The process might be continued, but take extra caution - Need attention INFO - Important business process has finished - each action that changes the state of the application significantly DEBUG - Developers stuff - When can not use debugger tool TRACE - Very detailed information, only for development but on production
  • 7. Logging Best Practices Do you know what you are logging? o Don’t generate NPE in log statements o Use ‘id’ of domain objects o Implement ‘toString()’ method for domain objects o Use ‘Arrays#deepToString’ o And read your logs often to spot incorrectly formatted messages log.debug("Processing request with id: {}", request.getId()); log.debug("Returning users: {}", users);
  • 8. Logging Best Practices Avoid side effects o Avoid log too much or improperly use toString() and/or string concatenation o Use SLF4J ‘Parameter Substitution’ feature try { log.trace("Id=" + request.getUser().getId() + " accesses " + manager.getPage().getUrl().toString()) } catch(NullPointerException e) { }
  • 9. Logging Best Practices Be concise and descriptive o Log files should be readable, clean and descriptive o Avoid logging everything o Don’t use magic numbers o Log values, numbers, ids and include their context o Not to log passwords and any personal information
  • 10. Logging Best Practices Be concise and descriptive log.debug(“Message processed”); log.debug(msg.getJMSMessageID()); log.debug("Message with id '{}' processed", msg.getJMSMessageID()); if(message instanceof TextMessage){ //... }Else{ log.warn("Unknown message type"); }
  • 11. Logging Best Practices Tune your pattern o In Logback <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppend er"> <encoder> <pattern>%d{HH:mm:ss.SSS} %-5level [%thread][%logger{0}] %m%n</pattern> </encoder> </appender>
  • 12. Logging Best Practices Tune your pattern o Use meaningful messages relevant to the context o Mapped Diagnostic Context (MDC) 2009-06-0508:15:23]INFO] User credentials entered 2009-06-0508:15:23]WARN] Incorrect PIN 2009-06-0508:15:37]INFO] User credentials entered 2009-06-0508:15:37]INFO] User credentials validated 2009-06-0508:15:46]INFO] Cash withdrawal requested 2009-06-0508:15:47]ERROR] Communication failure Acme.ATM.Integration.ServerException: Unable to connect to bank server ...
  • 13. Logging Best Practices Log method arguments and return values o It is always better to have too much rather than too few logging statements o Your code should be covered with logging routines as it is with unit tests o Use DEBUG or TRACE levels
  • 14. Logging Best Practices Watch out for external systems o Log every piece of data that comes out from your application and gets in o Be extra careful when integrating with external systems and prepare to pay that cost o Use different log levels
  • 15. Logging Best Practices Log exceptions properly o Avoid logging exceptions o Not all exceptions are errors o Log OR wrap and throw back Try { //…. Catch (Exception e) { log.error(“IO Exception”, e); Throw new MyCustomException(e); }
  • 16. Logging Best Practices Log exceptions properly   Try { Integer x = null; ++x; }Catch (Exception e) { log.error(e.toString());        //A log.error(e.getMessage());        //B log.error("", e); //C log.error("{}", e.getMessage());        //D log.error("Error reading configuration file: " + e);        //E log.error("Error reading configuration file: " + e.getFile());       //F log.error("Error reading configuration file ", e); //G        Throw new MyCustomException(e); }