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

一、简述

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

 

二、教程

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

    <dependencies>
        
        
        <dependency>
            <groupId>ch.qos.logbackgroupId>
            <artifactId>logback-classicartifactId>
            <version>1.2.3version>
        dependency>
        
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-apiartifactId>
            <version>1.7.25version>
        dependency>
        
        
        <dependency>
            <groupId>net.logstash.logbackgroupId>
            <artifactId>logstash-logback-encoderartifactId>
            <version>5.2version>
        dependency>
        
    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%npattern>
        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.gzfileNamePattern>
            <maxHistory>7maxHistory>
        rollingPolicy>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%npattern>
        encoder>
    appender>
    <appender name="LogStash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
        <destination>172.16.4.141:5044destination>
        <encoder charset="UTF-8" class="net.logstash.logback.encoder.LogstashEncoder">
            <customFields>{"appName":"myapp-service"}customFields>
        encoder>
        <connectionStrategy>
            <roundRobin>
                <connectionTTL>5 minutesconnectionTTL>
            roundRobin>
        connectionStrategy>
    appender>
    <root level="INFO">
        <appender-ref ref="File"/>
        <appender-ref ref="Console"/>
        <appender-ref ref="LogStash"/>
    root>
configuration>

 

  2、写程序发送日志

package com.yungoal.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.");
    }
}

 

三、效果

JAVA使用Logback发送日志到控制台、文件、ELK的最简单用法_第1张图片

 

转载于:https://www.cnblogs.com/songxingzhu/p/10239881.html

你可能感兴趣的:(JAVA使用Logback发送日志到控制台、文件、ELK的最简单用法)