Good afternoon Bug Whisperers 🐞. Writing code without proper logging in Java can cause issues affecting debugging, maintenance, and system reliability.
Problems that come with code without logging:
1. Difficulty in Debugging Issues
Diagnosing issues in production or development environments becomes challenging.
You have to do guesswork due to the lack of context about the code's execution flow.
2. Lack of Visibility
- It becomes impossible to monitor critical operations like database queries, API calls, or configuration changes.
3. Missed Metrics and Alerts
Provide important metrics (e.g., frequency of exceptions, error rates).
What is Logging in Java
Logging is an integral and indispensable aspect of the software development process. It empowers developers to effectively monitor and troubleshoot applications by gathering and analyzing pertinent data. By identifying potential issues and bugs, logging plays a pivotal role in enhancing code quality and optimizing performance.
In this comprehensive tutorial, I will delve into the realm of best practices for creating a robust logging system tailored for Java applications.
Here are logging methods provided in Java:
1. Using logging framework
Java has built-in logging functionality provided by the java.util.logging package. However, even though it is effortless to set up and use, it only offers basic logging features, making it unsuitable for production-ready applications.
For building large scale applications, you need a more robust logging solution with the following features:
- The framework should be able to log events in a structured format such as JSON, Logfmt, and so on.
- It should allow you to include contextual information that describes the logged event.
- It should have a centralized configuration system that allows you to configure the logging system in one place without altering the application code.
- Other features such as filtering, asynchronous logging, detailed documentation, good community support, and so on.
To get all the above features, you have to use a logging framework. In Java the most polar ones are Log4j and Logback
Be sure to read more in the links I provided 👆
2. Use SLF4J
Provides an interface that works on top of other logging frameworks, allowing developers to switch the underlying logging frameworks without having to change any code.
For example, you could set up Log4j to work with SLF4J. First, make sure you have the following dependencies in your pom.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>java-logging-slf4j-log4j</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>20</maven.compiler.source>
<maven.compiler.target>20</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.20.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.20.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j2-impl</artifactId>
<version>2.20.0</version>
</dependency>
</dependencies>
</project>
log4j-api
and log4j-core
are the main components of Log4j
, and log4j-slf4j2-impl
is Log4j's
SLF4J
binding, which allows SLF4J's
API to use Log4j
as its backend.
And then you could configure this logging system as you would with a standard Log4j
setup.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
<Properties>
<Property name="LOG_PATTERN">%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n</Property>
</Properties>
<Appenders>
<Console name="console" target="SYSTEM_OUT" follow="true">
<PatternLayout pattern="${LOG_PATTERN}"/>
</Console>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="console"/>
</Root>
</Loggers>
</Configuration>
Lastly, use SLF4J
's API to make a logging call instead of Log4j
.
package org.example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(Main.class);
logger.info("Hello world!");
}
}
Output
2023-04-13 16:46:09 INFO Main - Hello world!
READMORE about logging in Java here
Top comments (0)