Table of Contents
1. Choose a Logging Framework (SLF4J Implementation)
Option A: SLF4J Logback (Recommended for simplicity)
Option B: SLF4J Log4j2
2. Write Logging Code Using SLF4J
3. Configure Logging Behavior via Configuration File
For Logback: Use logback.xml
For Log4j2: Use log4j2.xml
4. Control Log Levels Dynamically (Optional)
5. Best Practices
Home Java javaTutorial How to configure logging in a Java application?

How to configure logging in a Java application?

Aug 15, 2025 am 11:50 AM
java Log configuration

Using SLF4J combined with Logback or Log4j2 is the recommended way to configure logs in Java applications. It introduces API and implementation libraries by adding corresponding Maven dependencies; 2. Obtain the logger through the LoggerFactory of SLF4J in the code, and write decoupled and efficient log code using parameterized logging methods; 3. Define log output format, level, target (console, file) and package-level log control through logback.xml or log4j2.xml configuration files; 4. Optionally enable the configuration file scanning function to achieve dynamic adjustment of log level, and Spring Boot can also be managed through Actuator endpoints; 5. Follow best practices, including avoiding recording sensitive information, reasonable use of log levels, and enabling log file scrolling to control disk occupation, thereby building a maintainable and high-performance log system.

How to configure logging in a Java application?

Configuring logging in a Java application is essential for monitoring, debugging, and maintaining applications in production. The most common and flexible approach today uses the SLF4J API with a backend implementation like Logback or Log4j2. Below is a practical guide to set up logging effectively.

How to configure logging in a Java application?

1. Choose a Logging Framework (SLF4J Implementation)

It's best practice to use SLF4J (Simple Logging Facade for Java) as the API, paired with a concrete logging framework like Logback or Log4j2 .

Add these dependencies to your pom.xml (for Maven):

How to configure logging in a Java application?
 <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>2.0.12</version>
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.4.11</version>
</dependency>

Logback automatically detects the SLF4J API and works out of the box.

Option B: SLF4J Log4j2

If you prefer Log4j2 (better performance, advanced features):

How to configure logging in a Java application?
 <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j2-impl</artifactId>
    <version>2.21.1</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.21.1</version>
</dependency>

Note: Log4j2 requires log4j-slf4j2-impl , not the older log4j-slf4j-impl .


2. Write Logging Code Using SLF4J

Use the SLF4J API in your Java classes:

 import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyApp {
    private static final Logger logger = LoggerFactory.getLogger(MyApp.class);

    public void doSomething() {
        logger.info("Starting operation");
        try {
            // some logic
            logger.debug("Processing item {}", "example");
        } catch (Exception e) {
            logger.error("Unexpected error occurred", e);
        }
    }
}

This keeps your code decoupled from the actual logging implementation.


3. Configure Logging Behavior via Configuration File

The behavior (log levels, output format, file output, etc.) is controlled by a config file.

For Logback: Use logback.xml

Place logback.xml in src/main/resources :

 <?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>logs/application.log</file>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- Set logging levels -->
    <root level="INFO">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="FILE"/>
    </root>

    <!-- Specific package level -->
    <logger name="com.example.myapp" level="DEBUG"/>
</configuration>

This setup logs to both console and file, with custom formatting.

For Log4j2: Use log4j2.xml

Place log4j2.xml in src/main/resources :

 <?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
        <File name="File" fileName="logs/app.log">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="File"/>
        </Root>
        <Logger name="com.example.myapp" level="debug"/>
    </Logers>
</Configuration>

4. Control Log Levels Dynamically (Optional)

You can change log levels at runtime if using web frameworks like Spring Boot:

  • Use Spring Boot Actuator with /actuator/loggers endpoint.
  • Or implement JMX-based log level control in standalone apps.

Alternatively, some apps reload config changes automatically:

  • Logback: Set <configuration scan="true" scanPeriod="30 seconds">
  • Log4j2: Add monitorInterval="30" to <Configuration>

5. Best Practices

  • Always use parameterized logging: logger.debug("User {} logged in from {}", user, ip);
  • Avoid logging sensitive data (passwords, tokens).
  • Use appropriate log levels:
    • ERROR : serious failures
    • WARN : potential issues
    • INFO : important lifecycle events
    • DEBUG : detailed info for troubleshooting
    • TRACE : very fine-grained data
  • Rotate log files using RollingFileAppender (Logback) or RollingFileAppender (Log4j2) to avoid huge files.

Example (Logback rolling file):

 <appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>logs/app.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>logs/app.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
        <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
            <maxFileSize>10MB</maxFileSize>
        </timeBasedFileNamingAndTriggeringPolicy>
        <maxHistory>30</maxHistory>
    </rollingPolicy>
    <encoder>
        <pattern>%d{ISO8601} %-5level %logger{36} - %msg%n</pattern>
    </encoder>
</appender>

That's it. With SLF4J and a solid backend like Logback, you get flexible, maintainable logging with minimal overhead. Most modern Java apps follow this pattern, and it scales well from small tools to large microservices.

The above is the detailed content of How to configure logging in a Java application?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is a deadlock in Java and how can you prevent it? What is a deadlock in Java and how can you prevent it? Aug 23, 2025 pm 12:55 PM

AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree

How to use Optional in Java? How to use Optional in Java? Aug 22, 2025 am 10:27 AM

UseOptional.empty(),Optional.of(),andOptional.ofNullable()tocreateOptionalinstancesdependingonwhetherthevalueisabsent,non-null,orpossiblynull.2.CheckforvaluessafelyusingisPresent()orpreferablyifPresent()toavoiddirectnullchecks.3.Providedefaultswithor

Java Persistence with Spring Data JPA and Hibernate Java Persistence with Spring Data JPA and Hibernate Aug 22, 2025 am 07:52 AM

The core of SpringDataJPA and Hibernate working together is: 1. JPA is the specification and Hibernate is the implementation, SpringDataJPA encapsulation simplifies DAO development; 2. Entity classes map database structures through @Entity, @Id, @Column, etc.; 3. Repository interface inherits JpaRepository to automatically implement CRUD and named query methods; 4. Complex queries use @Query annotation to support JPQL or native SQL; 5. In SpringBoot, integration is completed by adding starter dependencies and configuring data sources and JPA attributes; 6. Transactions are made by @Transactiona

Java Cryptography Architecture (JCA) for Secure Coding Java Cryptography Architecture (JCA) for Secure Coding Aug 23, 2025 pm 01:20 PM

Understand JCA core components such as MessageDigest, Cipher, KeyGenerator, SecureRandom, Signature, KeyStore, etc., which implement algorithms through the provider mechanism; 2. Use strong algorithms and parameters such as SHA-256/SHA-512, AES (256-bit key, GCM mode), RSA (2048-bit or above) and SecureRandom; 3. Avoid hard-coded keys, use KeyStore to manage keys, and generate keys through securely derived passwords such as PBKDF2; 4. Disable ECB mode, adopt authentication encryption modes such as GCM, use unique random IVs for each encryption, and clear sensitive ones in time

LOL Game Settings Not Saving After Closing [FIXED] LOL Game Settings Not Saving After Closing [FIXED] Aug 24, 2025 am 03:17 AM

IfLeagueofLegendssettingsaren’tsaving,trythesesteps:1.Runthegameasadministrator.2.GrantfullfolderpermissionstotheLeagueofLegendsdirectory.3.Editandensuregame.cfgisn’tread-only.4.Disablecloudsyncforthegamefolder.5.RepairthegameviatheRiotClient.

How to use the Pattern and Matcher classes in Java? How to use the Pattern and Matcher classes in Java? Aug 22, 2025 am 09:57 AM

The Pattern class is used to compile regular expressions, and the Matcher class is used to perform matching operations on strings. The combination of the two can realize text search, matching and replacement; first create a pattern object through Pattern.compile(), and then call its matcher() method to generate a Matcher instance. Then use matches() to judge the full string matching, find() to find subsequences, replaceAll() or replaceFirst() for replacement. If the regular contains a capture group, the nth group content can be obtained through group(n). In actual applications, you should avoid repeated compilation patterns, pay attention to special character escapes, and use the matching pattern flag as needed, and ultimately achieve efficient

Edit bookmarks in chrome Edit bookmarks in chrome Aug 27, 2025 am 12:03 AM

Chrome bookmark editing is simple and practical. Users can enter the bookmark manager through the shortcut keys Ctrl Shift O (Windows) or Cmd Shift O (Mac), or enter through the browser menu; 1. When editing a single bookmark, right-click to select "Edit", modify the title or URL and click "Finish" to save; 2. When organizing bookmarks in batches, you can hold Ctrl (or Cmd) to multiple-choice bookmarks in the bookmark manager, right-click to select "Move to" or "Copy to" the target folder; 3. When exporting and importing bookmarks, click the "Solve" button to select "Export Bookmark" to save as HTML file, and then restore it through the "Import Bookmark" function if necessary.

'Java is not recognized' Error in CMD [3 Simple Steps] 'Java is not recognized' Error in CMD [3 Simple Steps] Aug 23, 2025 am 01:50 AM

IfJavaisnotrecognizedinCMD,ensureJavaisinstalled,settheJAVA_HOMEvariabletotheJDKpath,andaddtheJDK'sbinfoldertothesystemPATH.RestartCMDandrunjava-versiontoconfirm.

See all articles