SlideShare a Scribd company logo
1 of 36
Logging with Logback
in Scala
Rishi Khandelwal
Software Consultant
Knoldus Software LLP
Agenda

Logging

Logback

Logback Architecture

Logback-classic-module

Configuration

Variable Substitution

Appenders
What is Logging ?
Logging is the process of recording application
actions and state to a secondary interface.
Logging Levels

TRACE

DEBUG

INFO

WARN

ERROR
Don't log everything.

Excessive logging is costly.

Performance will be affected.

Take a long time to analyze important
information
Logback ???

Logback is intended as a successor to the popular log4j project.

Logback is divided into three modules
logback-core
logback-classic
logback-access

logback-core module lays the groundwork for the other two modules.

logback-classic natively implements the SLF4J API

logback-access module integrates with Servlet containers, such as
Tomcat and Jetty
Logback-classic-module

Built upon three main classes: Logger,
Appender and Layout

Logger → logback-classic

Appender & layout → logback-core
Logger Context

It is the logging space which is categorized according to developer-chosen
criteria.

Every single logger is attached to a LoggerContext.

It is responsible for arranging loggers in a tree like hierarchy.

Loggers are named entities which is case-sensitive.

They follow the hierarchical naming rule.
Named Hierarchy
A logger is said to be an ancestor of another logger if its name followed by a dot is
prefix of the descendant logger name.
A logger is said to be a parent of a child logger if there are no ancestors between
itself and the descendant logger.
"com.foo" is a parent of the logger named "com.foo.Bar".
"java" is a parent of "java.util" and an ancestor of "java.util.Vector".
Root Logger
The root logger resides at the top of the logger hierarchy. It is
exceptional in that it is part of every hierarchy at its inception.
Like every logger, it can be retrieved by its name, as follows:
val rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME)
Other methods :
package org.slf4j;
public interface Logger {
// Printing methods:
public void trace(String message);
public void debug(String message);
public void info(String message);
Effective Level

Loggers may be assigned levels

If a given logger is not assigned a level, then it inherits one from its closest
ancestor with an assigned level

The root logger always has an assigned level. By default, this is DEBUG.
The effective level for a given logger L, is equal to the first non-null level in its
hierarchy, starting at L itself and proceeding upwards in the hierarchy
towards the root logger.
Basic Selection Rule
A log request of level p issued to a logger having an effective level q, is enabled if p >=
q.
levels order: TRACE < DEBUG < INFO < WARN < ERROR.
Configuration

Logback tries to find a file called logback.groovy in the classpath.

If no such file is found, logback tries to find a file called logback-test.xml in the
classpath.

If no such file is found, it checks for the file logback.xml in the classpath..

If neither file is found, logback configures itself automatically using the
BasicConfigurator which will cause logging output to be directed to the console.
logback.xml
Printing status messages
<configuration debug="true">
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender"
>
<!-- encoders are assigned the type
ch.qos.logback.classic.encoder.PatternLayoutE
ncoder by default -->
<encoder>
Automatically reloading configuration file
upon modification
<configuration scan="true">
...
</configuration>
For scan periods :
<configuration scan="true" scanPeriod="30 seconds" >
...
</configuration>
Configuration file syntax

Case sensitivity of tag names

Configuring loggers, or the <logger> element

Configuring the root logger, or the <root> element

Configuring Appenders
<configuration>
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>
%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="com.configuration" level="INFO" />
<logger name="chapters.configuration.Foo" level="DEBUG" />
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
</configuration>
<configuration>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>myApp.log</file>
<encoder>
<pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
</encoder>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%msg%n</pattern>
</encoder>
</appender>
<logger name="chapters.configuration">
<appender-ref ref="FILE" />
</logger>
<root level="debug">
<appender-ref ref="STDOUT" />
</root>
</configuration>
Variable Substitution
Simple substitution :
<configuration>
<property name="USER_HOME"
value="/home/rishi/Application/blog_projects/kn
olx/src/main/resources/log" />
<appender name="FILE"
class="ch.qos.logback.core.FileAppender">
<file>${USER_HOME}/myApp.log</file>
Variable Substitution
System Variable substitution :
<configuration>
<appender name="FILE"
class="ch.qos.logback.core.FileAppender">
<file>${USER_HOME}/myApp.log</file>
<encoder>
<pattern>%msg%n</pattern>
</encoder>
Variable Substitution
Variable substitution using a separate file :
<configuration>
<property
file="/home/rishi/Application/blog_projects/knol
x/src/main/resources/variable.properties" />
<appender name="FILE"
class="ch.qos.logback.core.FileAppender">
<file>${USER_HOME}/myApp.log</file>
Conditional processing
<!-- if-then form -->
<if condition="some conditional expression">
<then>
...
</then>
</if>
<!-- if-then-else form -->
<if condition="some conditional expression">
<then>
...
</then>
Appenders
Logback delegates the task of writing a logging event to components called
appenders Logback-core
Console Appender
OutputStreamAppender File Appender
Rolling File Appender
Time Based Size based Fixed Window
Console Appender
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern>
</encoder>
</appender>
File Appender :
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>testFile.log</file>
<encoder>
<pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
</encoder>
</appender>
Time base rolling :
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>logFile.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- daily rollover -->
<fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- keep 30 days' worth of history -->
<maxHistory>30</maxHistory>
</rollingPolicy>
Fixed Window :
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<fileNamePattern>tests.%i.log.zip</fileNamePattern>
<minIndex>1</minIndex>
<maxIndex>3</maxIndex>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>5MB</maxFileSize>
</triggeringPolicy>
Size and Time based :
<appender name="ROLLING"
class="ch.qos.logback.core.rolling.RollingFileA
ppender">
<file>mylog.txt</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBased
RollingPolicy">
<!-- rollover daily -->
<fileNamePattern>mylog-%d{yyyy-MM-dd}.
%i.txt</fileNamePattern>
SMTP Appender :
<appender name="EMAIL"
class="ch.qos.logback.classic.net.SMTPAppender">
<smtpHost>smtp.gmail.com</smtpHost>
<smtpPort>587</smtpPort>
<STARTTLS>true</STARTTLS>
<username>USERNAMNE</username>
<password>PASSWORD</password>
<asynchronousSending>false</asynchronousSending>
<to>EMAIL_IDS</to>
<from>NAME</from>
<subject>ERROR: %logger{20} - %m</subject>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%date %-5level %logger - %message%n</pattern>
</layout>
Logging with Logback in Scala

More Related Content

What's hot

Crud tutorial en
Crud tutorial enCrud tutorial en
Crud tutorial en
forkgrown
 

What's hot (20)

Apache Calcite overview
Apache Calcite overviewApache Calcite overview
Apache Calcite overview
 
Java 17
Java 17Java 17
Java 17
 
Python/Flask Presentation
Python/Flask PresentationPython/Flask Presentation
Python/Flask Presentation
 
Hive User Meeting August 2009 Facebook
Hive User Meeting August 2009 FacebookHive User Meeting August 2009 Facebook
Hive User Meeting August 2009 Facebook
 
Spark Streaming | Twitter Sentiment Analysis Example | Apache Spark Training ...
Spark Streaming | Twitter Sentiment Analysis Example | Apache Spark Training ...Spark Streaming | Twitter Sentiment Analysis Example | Apache Spark Training ...
Spark Streaming | Twitter Sentiment Analysis Example | Apache Spark Training ...
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Spark and the Hadoop Ecosystem: Best Practices for Amazon EMR
Spark and the Hadoop Ecosystem: Best Practices for Amazon EMRSpark and the Hadoop Ecosystem: Best Practices for Amazon EMR
Spark and the Hadoop Ecosystem: Best Practices for Amazon EMR
 
Crud tutorial en
Crud tutorial enCrud tutorial en
Crud tutorial en
 
RESTful API Design, Second Edition
RESTful API Design, Second EditionRESTful API Design, Second Edition
RESTful API Design, Second Edition
 
Neo4j Stored Procedure Training Part 2
Neo4j Stored Procedure Training Part 2Neo4j Stored Procedure Training Part 2
Neo4j Stored Procedure Training Part 2
 
TDD and Unit Testing in Golang
TDD and Unit Testing in GolangTDD and Unit Testing in Golang
TDD and Unit Testing in Golang
 
Introduction to Apache solr
Introduction to Apache solrIntroduction to Apache solr
Introduction to Apache solr
 
Apache Flink internals
Apache Flink internalsApache Flink internals
Apache Flink internals
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Introduction to Google Guice
Introduction to Google GuiceIntroduction to Google Guice
Introduction to Google Guice
 
Deep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKDeep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UK
 
Modern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafModern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and Thymeleaf
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 

Viewers also liked

Manual de instalacion Piranha
Manual de instalacion PiranhaManual de instalacion Piranha
Manual de instalacion Piranha
lagreda76
 
Apache Phoenix: Transforming HBase into a SQL Database
Apache Phoenix: Transforming HBase into a SQL DatabaseApache Phoenix: Transforming HBase into a SQL Database
Apache Phoenix: Transforming HBase into a SQL Database
DataWorks Summit
 

Viewers also liked (11)

Logging in Scala
Logging in ScalaLogging in Scala
Logging in Scala
 
Jsp project module
Jsp project moduleJsp project module
Jsp project module
 
Scala + Akka + ning/async-http-client - Vancouver Scala meetup February 2015
Scala + Akka + ning/async-http-client - Vancouver Scala meetup February 2015Scala + Akka + ning/async-http-client - Vancouver Scala meetup February 2015
Scala + Akka + ning/async-http-client - Vancouver Scala meetup February 2015
 
Logging with Logback in Scala
Logging with Logback in ScalaLogging with Logback in Scala
Logging with Logback in Scala
 
Manual de instalacion Piranha
Manual de instalacion PiranhaManual de instalacion Piranha
Manual de instalacion Piranha
 
Piranha
PiranhaPiranha
Piranha
 
Apache Phoenix: Transforming HBase into a SQL Database
Apache Phoenix: Transforming HBase into a SQL DatabaseApache Phoenix: Transforming HBase into a SQL Database
Apache Phoenix: Transforming HBase into a SQL Database
 
Rimas del otoño
Rimas del otoñoRimas del otoño
Rimas del otoño
 
Unit testing of spark applications
Unit testing of spark applicationsUnit testing of spark applications
Unit testing of spark applications
 
BDD with Cucumber
BDD with CucumberBDD with Cucumber
BDD with Cucumber
 
Introduction to AWS IAM
Introduction to AWS IAMIntroduction to AWS IAM
Introduction to AWS IAM
 

Similar to Logging with Logback in Scala

LOGBack and SLF4J
LOGBack and SLF4JLOGBack and SLF4J
LOGBack and SLF4J
jkumaranc
 
LOGBack and SLF4J
LOGBack and SLF4JLOGBack and SLF4J
LOGBack and SLF4J
jkumaranc
 
Java Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4jJava Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4j
Rajiv Gupta
 

Similar to Logging with Logback in Scala (20)

Logback
LogbackLogback
Logback
 
Log4j in 8 slides
Log4j in 8 slidesLog4j in 8 slides
Log4j in 8 slides
 
Log4j2
Log4j2Log4j2
Log4j2
 
Logging
LoggingLogging
Logging
 
Log4j
Log4jLog4j
Log4j
 
LOGBack and SLF4J
LOGBack and SLF4JLOGBack and SLF4J
LOGBack and SLF4J
 
LOGBack and SLF4J
LOGBack and SLF4JLOGBack and SLF4J
LOGBack and SLF4J
 
LOGBack and SLF4J
LOGBack and SLF4JLOGBack and SLF4J
LOGBack and SLF4J
 
LOGBack and SLF4J
LOGBack and SLF4JLOGBack and SLF4J
LOGBack and SLF4J
 
11i Logs
11i Logs11i Logs
11i Logs
 
Java Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4jJava Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4j
 
Application Logging in the 21st century - 2014.key
Application Logging in the 21st century - 2014.keyApplication Logging in the 21st century - 2014.key
Application Logging in the 21st century - 2014.key
 
Logging, Serilog, Structured Logging, Seq
Logging, Serilog, Structured Logging, SeqLogging, Serilog, Structured Logging, Seq
Logging, Serilog, Structured Logging, Seq
 
Log4j Logging Mechanism
Log4j Logging MechanismLog4j Logging Mechanism
Log4j Logging Mechanism
 
Log4jxml ex
Log4jxml exLog4jxml ex
Log4jxml ex
 
Odoo command line interface
Odoo command line interfaceOdoo command line interface
Odoo command line interface
 
Software Engineering - RS4
Software Engineering - RS4Software Engineering - RS4
Software Engineering - RS4
 
Rein_in_the_ability_of_log4j
Rein_in_the_ability_of_log4jRein_in_the_ability_of_log4j
Rein_in_the_ability_of_log4j
 
Troubleshooting PostgreSQL Streaming Replication
Troubleshooting PostgreSQL Streaming ReplicationTroubleshooting PostgreSQL Streaming Replication
Troubleshooting PostgreSQL Streaming Replication
 
Log4e
Log4eLog4e
Log4e
 

More from Knoldus Inc.

More from Knoldus Inc. (20)

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

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...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 

Logging with Logback in Scala

  • 1. Logging with Logback in Scala Rishi Khandelwal Software Consultant Knoldus Software LLP
  • 4. Logging is the process of recording application actions and state to a secondary interface.
  • 7.  Excessive logging is costly.  Performance will be affected.  Take a long time to analyze important information
  • 9.  Logback is intended as a successor to the popular log4j project.  Logback is divided into three modules logback-core logback-classic logback-access  logback-core module lays the groundwork for the other two modules.  logback-classic natively implements the SLF4J API  logback-access module integrates with Servlet containers, such as Tomcat and Jetty
  • 10.
  • 11. Logback-classic-module  Built upon three main classes: Logger, Appender and Layout  Logger → logback-classic  Appender & layout → logback-core
  • 12. Logger Context  It is the logging space which is categorized according to developer-chosen criteria.  Every single logger is attached to a LoggerContext.  It is responsible for arranging loggers in a tree like hierarchy.  Loggers are named entities which is case-sensitive.  They follow the hierarchical naming rule.
  • 13. Named Hierarchy A logger is said to be an ancestor of another logger if its name followed by a dot is prefix of the descendant logger name. A logger is said to be a parent of a child logger if there are no ancestors between itself and the descendant logger. "com.foo" is a parent of the logger named "com.foo.Bar". "java" is a parent of "java.util" and an ancestor of "java.util.Vector".
  • 14. Root Logger The root logger resides at the top of the logger hierarchy. It is exceptional in that it is part of every hierarchy at its inception. Like every logger, it can be retrieved by its name, as follows: val rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME) Other methods : package org.slf4j; public interface Logger { // Printing methods: public void trace(String message); public void debug(String message); public void info(String message);
  • 15. Effective Level  Loggers may be assigned levels  If a given logger is not assigned a level, then it inherits one from its closest ancestor with an assigned level  The root logger always has an assigned level. By default, this is DEBUG. The effective level for a given logger L, is equal to the first non-null level in its hierarchy, starting at L itself and proceeding upwards in the hierarchy towards the root logger.
  • 16.
  • 17. Basic Selection Rule A log request of level p issued to a logger having an effective level q, is enabled if p >= q. levels order: TRACE < DEBUG < INFO < WARN < ERROR.
  • 18. Configuration  Logback tries to find a file called logback.groovy in the classpath.  If no such file is found, logback tries to find a file called logback-test.xml in the classpath.  If no such file is found, it checks for the file logback.xml in the classpath..  If neither file is found, logback configures itself automatically using the BasicConfigurator which will cause logging output to be directed to the console.
  • 20. Printing status messages <configuration debug="true"> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender" > <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutE ncoder by default --> <encoder>
  • 21. Automatically reloading configuration file upon modification <configuration scan="true"> ... </configuration> For scan periods : <configuration scan="true" scanPeriod="30 seconds" > ... </configuration>
  • 23.  Case sensitivity of tag names  Configuring loggers, or the <logger> element  Configuring the root logger, or the <root> element  Configuring Appenders
  • 24. <configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern> %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n </pattern> </encoder> </appender> <logger name="com.configuration" level="INFO" /> <logger name="chapters.configuration.Foo" level="DEBUG" /> <root level="DEBUG"> <appender-ref ref="STDOUT" /> </root> </configuration>
  • 25. <configuration> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>myApp.log</file> <encoder> <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern> </encoder> </appender> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%msg%n</pattern> </encoder> </appender> <logger name="chapters.configuration"> <appender-ref ref="FILE" /> </logger> <root level="debug"> <appender-ref ref="STDOUT" /> </root> </configuration>
  • 26. Variable Substitution Simple substitution : <configuration> <property name="USER_HOME" value="/home/rishi/Application/blog_projects/kn olx/src/main/resources/log" /> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>${USER_HOME}/myApp.log</file>
  • 27. Variable Substitution System Variable substitution : <configuration> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>${USER_HOME}/myApp.log</file> <encoder> <pattern>%msg%n</pattern> </encoder>
  • 28. Variable Substitution Variable substitution using a separate file : <configuration> <property file="/home/rishi/Application/blog_projects/knol x/src/main/resources/variable.properties" /> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>${USER_HOME}/myApp.log</file>
  • 29. Conditional processing <!-- if-then form --> <if condition="some conditional expression"> <then> ... </then> </if> <!-- if-then-else form --> <if condition="some conditional expression"> <then> ... </then>
  • 30. Appenders Logback delegates the task of writing a logging event to components called appenders Logback-core Console Appender OutputStreamAppender File Appender Rolling File Appender Time Based Size based Fixed Window
  • 31. Console Appender <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern> </encoder> </appender> File Appender : <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>testFile.log</file> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender>
  • 32. Time base rolling : <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>logFile.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- daily rollover --> <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern> <!-- keep 30 days' worth of history --> <maxHistory>30</maxHistory> </rollingPolicy>
  • 33. Fixed Window : <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> <fileNamePattern>tests.%i.log.zip</fileNamePattern> <minIndex>1</minIndex> <maxIndex>3</maxIndex> </rollingPolicy> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <maxFileSize>5MB</maxFileSize> </triggeringPolicy>
  • 34. Size and Time based : <appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileA ppender"> <file>mylog.txt</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBased RollingPolicy"> <!-- rollover daily --> <fileNamePattern>mylog-%d{yyyy-MM-dd}. %i.txt</fileNamePattern>
  • 35. SMTP Appender : <appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender"> <smtpHost>smtp.gmail.com</smtpHost> <smtpPort>587</smtpPort> <STARTTLS>true</STARTTLS> <username>USERNAMNE</username> <password>PASSWORD</password> <asynchronousSending>false</asynchronousSending> <to>EMAIL_IDS</to> <from>NAME</from> <subject>ERROR: %logger{20} - %m</subject> <layout class="ch.qos.logback.classic.PatternLayout"> <pattern>%date %-5level %logger - %message%n</pattern> </layout>