DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • ITBench, Part 1: Next-Gen Benchmarking for IT Automation Evaluation
  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  • Vision AI on Apple Silicon: A Practical Guide to MLX-VLM
  • Feature Flag Framework in Salesforce Using LaunchDarkly

Trending

  • Go 1.24+ Native FIPS Support for Easier Compliance
  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  1. DZone
  2. Coding
  3. Frameworks
  4. SLF4J with Logback

SLF4J with Logback

By 
Sam Kyatham user avatar
Sam Kyatham
·
Mar. 08, 13 · Interview
Likes (2)
Comment
Save
Tweet
Share
15.4K Views

Join the DZone community and get the full member experience.

Join For Free

It is common that most of the developers use their own logging frameworks at the time of development and that force organizations to maintain configuration for each logging framework. Normally switching from logging level from DEBUG to INFO sometimes requires a application restart in production. SLF4J is the latest logging facade helps to plug-in desired logging framework at deployment time. The article further talks about usage of the SLF4J with logback. 

SLF4J - Simple Logging Facade for Java API helps to plug-in desired logging implementation at deployment time.

Logback - helps to change logging configuration through JMX at runtime with out restarting your applications in production.

I hope this article helps to get high level overview of SLF4J/Logback and migrating your existing apps to common logging approach.  

SLF4J

This is simple logging façade to abstract the various logging frameworks such as logback, log4j, commons-logging and default java logging implementation (java.util.logging). This primarily enables the user to inlcude desired logging framework at deployment time. It is lightweight and nearly adds a zero overhead on performance.

Note that SLF4j doesn’t replace any logging framework; it is just a façade around any standard logging framework. If slf4j doesn’t find any logging framwork in classpath, by default it prints the logs in console.

Logback

This is an improved version of log4j and natively supports the slf4j, hence migrating from other logging frameworks such as log4j and java.util.logging is quite possible.

Since the logback natively supports slf4j, the combination of using slf4j with this framework is relatively faster than the slf4j with other logging frameworks. Logging configuration can be done either in xml or groovy.

*One important feature is that it exposes the configuration through JMX hence configuration (debug to info etc) can be changed via JMX console with out restarting the application.

Also, it does print the artifact version as part of the exception stacktrace that may be helpful for debugging.

java.lang.NullPointerException: null

  at com.fimt.poc.LoggingSample.<init>(LoggingSample.java:16) [classes/:na]

  at com.fimt.poc.LoggingSample.main(LoggingSample.java:23) [fimt-logging-poc-1.0.jar/:1.0]

**Reasons to prefer logback over log4j is well explainedhere

SLF4J api usage in java classes

(1)  Import the Logger and LoggerFactory from org.slf4j package

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

(2) Declare the logger class as,

private final Logger logger = LoggerFactory.getLogger(LoggingSample.class);

(3) Use debug, warn, info, error and trace with appropriate parameters. All methods by default takes the string as an input.

logger.info("This is sample info statement");

SLF4J with Logback

Include the following dependency pom.xml, it pulls its depedencies logback-core and slf4j-api in addition to logback-classic

<dependency>

  <groupId>ch.qos.logback</groupId>

  <artifactId>logback-classic</artifactId>

  <version>1.0.7</version>

  </dependency>

SLF4J can be used with existing logging framworks log4j, common-logging and java.util.logging (JUL). Required dependencies are mentioned below.

SLF4J with Log4j

Include the following dependency pom.xml, it pulls its depedencies log4jand slf4j-api in addition to slf4j-log4j12 artifact.

<dependency>

  <groupId>org.slf4j</groupId>

  <artifactId>slf4j-log4j12</artifactId>

  <version>1.7.2</version>

  </dependency>

SLF4J with JUL (java.util.logging)

Include the following dependency pom.xml, it pulls its depedency slf4j-api in addition to slf4j-jdk14 artifact.

<dependency>

  <groupId>org.slf4j</groupId>

  <artifactId>slf4j-jdk14</artifactId>

  <version>1.7.2</version>

  </dependency>

Migrating existing projects logging to logback framework

Step: 1 – Update existing project pom.xml

Add the right dependency mentioned above. Also remove the unused log4j/commons logging dependencies.

Step: 2 – Update java files with SLF4J API

Scan all java files and replace log4j or java.util.logging classes in to SLF4J api classes. This can be done using the tool java -jar slf4j-migrator-1.7.2.jar . Detailed documentation and limitation is mentioned here

This tool replaces the logging apis of log4j, commons-logging and java.util.logging in to SLF4J API classes.

Step: 3 – Convert log4j.properties to logback.xml

Logback provides a online translator which converts log4j properties in to logback.xml 

File Appenders:

Like other logging frameworks, logback implementation also supports various file appenders.

Daily file rolling:

<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">

  <FileNamePattern>logFile.%d{yyyy-MM-dd}.log</FileNamePattern>

  <!-- keep 30 days' worth of history -->

  <maxHistory>30</maxHistory>

</rollingPolicy>

Roll log files based on size:

<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">

  <fileNamePattern>tests.%i.log.zip</fileNamePattern>

  <minIndex>1</minIndex>

  <maxIndex>10</maxIndex>

</rollingPolicy>

<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">

  <maxFileSize>5MB</maxFileSize>

</triggeringPolicy>

Layout

<layout class="ch.qos.logback.classic.PatternLayout">

  <Pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</Pattern>

</layout>
Log4j Framework

Opinions expressed by DZone contributors are their own.

Related

  • ITBench, Part 1: Next-Gen Benchmarking for IT Automation Evaluation
  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  • Vision AI on Apple Silicon: A Practical Guide to MLX-VLM
  • Feature Flag Framework in Salesforce Using LaunchDarkly

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!