SLF4J Logback教程

登录徽标

一个带有Logback示例的简单SLF4J

经过测试

  • SLF4J API 1.7.25
  • 回退1.2.3
  • Maven 3
  • Java 8

注意
Logback本机实现SLF4J API。

1.项目目录

项目目录

2. Maven

2.1声明logback-classic ,它将slf4j-api logback-coreslf4j-api

pom.xml
<dependency>
		<groupId>ch.qos.logback</groupId>
		<artifactId>logback-classic</artifactId>
		<version>1.2.3</version>
	</dependency>
com.mkyong:slf4j-logback:jar:1.0
[INFO] +- ch.qos.logback:logback-classic:jar:1.2.3:compile
[INFO] |  +- ch.qos.logback:logback-core:jar:1.2.3:compile
[INFO] |  \- org.slf4j:slf4j-api:jar:1.7.25:compile

2.2完整的pom.xml示例。

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>com.mkyong</groupId>
    <artifactId>slf4j-logback</artifactId>
    <version>1.0</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <logback.version>1.2.3</logback.version>
		<javax.mail.version>1.6.2</javax.mail.version>
    </properties>

    <dependencies>

        <!-- pull in logback-core and slf4j-api -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
        </dependency>

        <!-- SMTPAppender need this to send email 
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>${javax.mail.version}</version>
        </dependency>
		-->
		
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>

            <!-- build a single executable JAR -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.0</version>
                <executions>
                    <!-- Attach the shade into the package phase -->
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.mkyong.HelloWorld</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>

</project>

3. logback.xml

3.1在项目类路径中创建logback.xml

src/resources/logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n
            </Pattern>
        </layout>
    </appender>

    <logger name="com.mkyong" level="debug" additivity="false">
        <appender-ref ref="CONSOLE"/>
    </logger>

    <root level="error">
        <appender-ref ref="CONSOLE"/>
    </root>

</configuration>

4.你好登录

HelloWorld.java
package com.mkyong;

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

public class HelloWorld {

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

    public static void main(String[] args) {

        logger.debug("Hello from Logback");

        logger.debug("getNumber() : {}", getNumber());

    }

    static int getNumber() {
        return 5;
    }

}

输出量

11:28:18.350 [main] DEBUG com.mkyong.HelloWorld - Hello from Logback
11:28:18.352 [main] DEBUG com.mkyong.HelloWorld - getNumber() : 5

5.登录配置

5.1对于开发,建议启用调试模式。 它会显示很多有用的信息,如果有的话也会显示错误信息。

logback.xml
<configuration debug="true">
    
</Configuration>

阅读此Logback配置

6. Logback Appenders

一些常见的Logback附加程序。

6.1 ConsoleAppender

logback.xml
<configuration>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n
            </Pattern>
        </layout>
    </appender>

    <logger name="com.mkyong" level="debug" additivity="false">
        <appender-ref ref="CONSOLE"/>
    </logger>

    <root level="error">
        <appender-ref ref="CONSOLE"/>
    </root>

</configuration>

6.2 FileAppender

logback.xml
<configuration>

    <property name="HOME_LOG" value="logs/app.log"/>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n
            </Pattern>
        </layout>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>${HOME_LOG}</file>
        <append>true</append>
        <immediateFlush>true</immediateFlush>
        <encoder>
            <pattern>%d %p %c{1.} [%t] %m%n</pattern>
        </encoder>
    </appender>

    <logger name="com.mkyong" level="debug" additivity="false">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="FILE"/>
    </logger>

    <root level="error">
        <appender-ref ref="CONSOLE"/>
    </root>

</configuration>
logs/app.log
2019-03-29 11:42:44,827 DEBUG com.mkyong.HelloWorld [main] Hello from Logback
2019-03-29 11:42:44,836 DEBUG com.mkyong.HelloWorld [main] getNumber() : 5

6.3 RollingFileAppender –按日期和大小旋转日志文件。 这是您生产中最需要的一种。

logback.xml
<configuration>

    <property name="HOME_LOG" value="logs/app.log"/>

    <appender name="FILE-ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${HOME_LOG}</file>

        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>logs/archived/app.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <!-- each archived file, size max 10MB -->
            <maxFileSize>10MB</maxFileSize>
            <!-- total size of all archive files, if total size > 20GB, it will delete old archived file -->
            <totalSizeCap>20GB</totalSizeCap>
            <!-- 60 days to keep -->
            <maxHistory>60</maxHistory>
        </rollingPolicy>

        <encoder>
            <pattern>%d %p %c{1.} [%t] %m%n</pattern>
        </encoder>
    </appender>

    <logger name="com.mkyong" level="debug" additivity="false">
        <appender-ref ref="FILE-ROLLING"/>
    </logger>

    <root level="error">
        <appender-ref ref="FILE-ROLLING"/>
    </root>

</configuration>
样品
样品

添加一个.gz扩展名,Logback将压缩存档文件。

logback.xml
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
		<fileNamePattern>logs/archived/app.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
	</rollingPolicy>
样品

6.4 SMTPAppender –需要javax.mail来发送电子邮件。

pom.xml
<dependency>
		<groupId>com.sun.mail</groupId>
		<artifactId>javax.mail</artifactId>
		<version>1.6.2</version>
	</dependency>
logback.xml
<configuration debug="true">

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n
            </Pattern>
        </layout>
    </appender>

    <appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
        <smtpHost>smtp.mailgun.org</smtpHost>
        <smtpPort>25</smtpPort>
        <username>123</username>
        <password>123</password>
        <to>TO_EMAIL</to>
        <to>RO_ANOTHER_EMAIL</to>
        <from>FROM_EMAIL</from>
        <subject>TESTING: %logger{20} - %m</subject>

        <layout class="ch.qos.logback.classic.html.HTMLLayout"/>

		<!-- for testing , comment in production, default 256 -->
        <cyclicBufferTracker class="ch.qos.logback.core.spi.CyclicBufferTracker">
			<!-- Send just one log entry per email, ready for a lot of emails if you put one. -->
            <bufferSize>1</bufferSize>
        </cyclicBufferTracker>

		<!-- for testing , comment in production, default asynchronousSending = true -->
        <asynchronousSending>false</asynchronousSending>

    </appender>

    <logger name="com.mkyong" level="error" additivity="false">
        <appender-ref ref="EMAIL"/>
    </logger>

    <root level="error">
        <appender-ref ref="CONSOLE"/>
    </root>

</configuration>

模拟错误

package com.mkyong;

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

public class HelloWorldError {

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

    public static void main(String[] args) {

        try {
            System.out.println(getData());
        } catch (IllegalArgumentException e) {
            logger.error("{}", e);
        }

    }

    static int getData() throws IllegalArgumentException {
        throw new IllegalArgumentException("Sorry IllegalArgumentException!");
    }

}

这是电子邮件

样本电子邮件

6.5 AsyncAppender –异步,更快地记录日志,但如果其队列已满80%,则丢弃TRACE,DEBUG和INFO级事件,仅保留WARN和ERROR级事件。 阅读此AsyncAppender

pom.xml
<configuration debug="true">

    <property name="HOME_LOG" value="logs/app.log"/>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n
            </Pattern>
        </layout>
    </appender>

    <appender name="FILE-ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${HOME_LOG}</file>

        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>logs/archived/app.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <!-- each archived file, size max 10MB -->
            <maxFileSize>10MB</maxFileSize>
            <!-- total size of all archive files, if total size > 20GB, it will delete old archived file -->
            <totalSizeCap>20GB</totalSizeCap>
            <!-- 60 days to keep -->
            <maxHistory>60</maxHistory>
        </rollingPolicy>

        <encoder>
            <pattern>%d %p %c{1.} [%t] %m%n</pattern>
        </encoder>
    </appender>

    <!-- https://logback.qos.ch/manual/appenders.html#AsyncAppender -->
    <!-- AsyncAppender will drop events of level TRACE, DEBUG and INFO if its queue is 80% full -->
    <appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
        <appender-ref ref="FILE-ROLLING" />
        <!-- defaulr 256 -->
        <queueSize>512</queueSize>
    </appender>

    <logger name="com.mkyong" level="debug" additivity="false">
        <appender-ref ref="ASYNC"/>
        <appender-ref ref="CONSOLE"/>
    </logger>

    <root level="error">
        <appender-ref ref="CONSOLE"/>
    </root>

</configuration>

注意
阅读更多Logback附加程序

下载源代码

$ git clone https://github.com/mkyong/java-logging.git
$ cd slf4j-logback
$ mvn清洁包
$ java -jar target \ slf4j-logback-1.0.jar

参考文献

翻译自: https://mkyong.com/logging/slf4j-logback-tutorial/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值