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

A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 

Último (20)

A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 

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); }