大数据

JAVA使用Logback发送日志到控制台、文件、ELK的最简单用法

宋兴柱 · 1月8日 · 2019年 · · · 1073次已读

一、简述

  本文讲JAVA使用Logback发送日志到控制台、文件、ELK的最简单用法。

 

二、教程

  1、新建pom.xml项目引入下列依赖:

    <dependencies>
        <!--Begin LogBack Log-->
        <!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <!--Logback to elk-->
        <!-- https://mvnrepository.com/artifact/net.logstash.logback/logstash-logback-encoder -->
        <dependency>
            <groupId>net.logstash.logback</groupId>
            <artifactId>logstash-logback-encoder</artifactId>
            <version>5.2</version>
        </dependency>
        <!--End LogBack Log-->
    </dependencies>

 

  2、在resources目录下添加logback.xml文件,将地址换成Logstash的地址,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
    <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
    <appender name="File" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>log/app.%d{yyyy-MM-dd}.log.tar.gz</fileNamePattern>
            <maxHistory>7</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
    <appender name="LogStash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
        <destination>127.0.0.1:5044</destination>
        <encoder charset="UTF-8" class="net.logstash.logback.encoder.LogstashEncoder">
            <customFields>{"appName":"myapp-service"}</customFields>
        </encoder>
        <connectionStrategy>
            <roundRobin>
                <connectionTTL>5 minutes</connectionTTL>
            </roundRobin>
        </connectionStrategy>
    </appender>
    <root level="INFO">
        <appender-ref ref="File"/>
        <appender-ref ref="Console"/>
        <appender-ref ref="LogStash"/>
    </root>
</configuration>

 

  2、写程序发送日志

package com.test.elktest;

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

public class Application {
    private static final Logger log = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {
        log.info("welcome to song xing zhu blogs.");
    }
}

 

三、效果

 

 
0 条回应