ELK菜鸟手记 (一) 环境配置+log4j日志记录-阿里云开发者社区

开发者社区> 开发与运维> 正文
登录阅读全文

ELK菜鸟手记 (一) 环境配置+log4j日志记录

简介: 1. 背景介绍 在大数据时代,日志记录和管理变得尤为重要。 以往的文件记录日志的形式,既查询起来又不方便,又造成日志在服务器上分散存储,管理起来相当麻烦, 想根据一个关键字查询日志中某个关键信息相当困难。

1. 背景介绍

在大数据时代,日志记录和管理变得尤为重要。

以往的文件记录日志的形式,既查询起来又不方便,又造成日志在服务器上分散存储,管理起来相当麻烦,

想根据一个关键字查询日志中某个关键信息相当困难。

这个时候,ELK诞生了。

什么是ELK?

简单来说:它是一套完整的日志记录和分析的解决方案平台

 

2. 技术栈介绍

ELK = Elasticsearch + Logstash + Kibana

2-1) Elasticsearch:

(

Elasticsearch is a distributed open source search engine based on Apache Lucene,

and released under an Apache 2.0 license (which means that it can be downloaded, used, and modi ed free of charge).

It provides horizontal scalability, reliability, and multitenant capability for real-time search.

Elasticsearch features are available through JSON over a RESTful API.

The searching capabilities are backed by a schema-less Apache Lucene Engine,

which allows it to dynamically index data without knowing the structure beforehand.

Elasticsearch is able to achieve fast search responses because it uses indexing to search over the texts. 

)

Elasticsearch是一个分布式的开源的基于Apache Lucene项目的搜索引擎,它发布在Apache 2.0协议下

(这也就意味着它可以被免费地下载,使用并且修改)。

 Elasticsearch提供了水平的,可扩展的,可靠的,多用户形式的实时搜索。

Elasticsearch的功能可以通过JSON格式的RESTful API形式访问。

Elasticsearch的搜索能力是得到Apache Lucene引擎的支持,允许给文本数据增加加动态索引。

 2-2) Logstash

(

Logstash is a data pipeline that helps collect, parse, and analyze a large variety of structured and unstructured data and events generated across various systems.

It provides plugins to connect to various types of input sources and platforms, and is designed to ef ciently process logs, events,

and unstructured data sources for distribution into a variety of outputs with the use of its output plugins,

namely le, stdout (as output on console running Logstash), or Elasticsearch. 

)

Logstash是一个数据管道,它被用来收集,解析和分析各种结构化的和非结构化的由各种系统产生的数据以及事件。

它提供了插件用来连接到各种输入数据源,可以高效地处理日志,事件以及非结构化的数据,而且可以通过输出插件的形式

把结果输出到各种输出源,比如:标准输出,控制台或者Elasticsearch。

 2-3) Kibana

(Kibana is an open source Apache 2.0 licensed data visualization platform that helps in

visualizing any kind of structured and unstructured data stored in Elasticsearch indexes.

Kibana is entirely written in HTML and JavaScript. )

Kibana是一个基于Apache 2.0协议的开源可视化平台,它用来可视化任何结构化的和非结构化的存储在Elasticsearch索引

中的数据。Kibana完全用HTML和Javascript编写。

 

3. 下载/安装/配置/启动

前面说了很多废话,接下来是每个程序员感兴趣的动手环节了,let's start!

3-1) 安装Elasticsearch

下载地址:

https://www.elastic.co/downloads/elasticsearch

a) 解压安装包elasticsearch-5.2.2.tar.gz

    (由于本人是mac系统)我把它解压到了/usr/local目录下,完整路径如下:

    /usr/local/elasticsearch-5.2.2

b) 编辑配置文件

   cd config

   vi elasticsearch.yml

   内容如下:

# ---------------------------------- Cluster -----------------------------------
#
# Use a descriptive name for your cluster:
#
cluster.name: my-application
#
# ------------------------------------ Node ------------------------------------
#
# Use a descriptive name for the node:
#
node.name: node-1
#
# Add custom attributes to the node:
#
#node.attr.rack: r1
#
# ----------------------------------- Paths ------------------------------------
#
# Path to directory where to store the data (separate multiple locations by comma):
#
path.data: /tmp/elasticsearch/data
#
# Path to log files:
#
path.logs: /tmp/elasticsearch/logs
# ---------------------------------- Network -----------------------------------
#
# Set the bind address to a specific IP (IPv4 or IPv6):
#
network.host: localhost
#
# Set a custom port for HTTP:
#
http.port: 9200

 

c) 启动Elasticsearch
./bin/elasticsearch

如果没有错误发生,可以进入到下一步的验证环节

d) 验证

可以使用cURL命令:

curl 'http://localhost:9200/?pretty'

或者

直接用浏览器打开

http://localhost:9200

 

3-2) 安装Logstash

a) 解压安装包logstash-5.2.2.tar.gz

    完整路径如下:

    /usr/local/logstash-5.2.2

b) 编辑配置文件

   cd config

   新建配置文件log4j_es.conf

   vi log4j_es.conf

   内容如下:

input {
    log4j {
        host => "127.0.0.1"
        port => 4560
    }
}

output {
    stdout {
      codec => rubydebug
    }
    elasticsearch{
        hosts => ["localhost:9200"]
        index => "log4j-%{+YYYY.MM.dd}"
        document_type => "log4j_type"
    }
}

c) 启动Logstash

./bin/logstash -f config/log4j-es.conf

 

3-3) 安装Kibana

a) 解压安装包kibana-5.2.2.tar.gz
完整路径如下:
/usr/local/ kibana-5.2.2


b) 编辑配置文件
cd config
vi kibana.yml
内容如下:

# Kibana is served by a back end server. This setting specifies the port to use.
server.port: 5601

server.host: "localhost"

# The URL of the Elasticsearch instance to use for all your queries.
elasticsearch.url: "http://localhost:9200"

# Kibana uses an index in Elasticsearch to store saved searches, visualizations and
# dashboards. Kibana creates a new index if the index doesn't already exist.
kibana.index: ".kibana"

c) 启动Kibana

./bin/kibana

 

d) 验证
打开网址:
http://localhost:5601/

见到如下Logo

 

4. Log4j记录日志到Logstash

4-1) 新建maven项目

pom中的关键dependency配置如下:

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

4-2) log4j.properties(放在resources文件夹下)

### 设置###
log4j.rootLogger = debug,stdout,D,E,logstash

### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

### 输出DEBUG 级别以上的日志到=/Users/bee/Documents/elk/log4j/debug.log###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = /Users/KG/Documents/logs/elk/debug.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### 输出ERROR 级别以上的日志到=/Users/bee/Documents/elk/log4j/error.log  ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =/Users/KG/Documents/logs/elk/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

#输出日志到logstash
log4j.appender.logstash=org.apache.log4j.net.SocketAppender
log4j.appender.logstash.RemoteHost=127.0.0.1
log4j.appender.logstash.port=4560
log4j.appender.logstash.ReconnectionDelay=60000
log4j.appender.logstash.LocationInfo=true

4-3) Java代码(ElkLog4jTest.java):

package org.genesis.arena.elk;

import org.apache.log4j.Logger;

/**
 * Created by KG on 17/3/27.
 */
public class ElkLog4jTest {
    private static final Logger logger = Logger.getLogger(ElkLog4jTest.class);
    public static void main(String[] args) throws Exception {
        logger.debug("This is a debug message!");
        logger.info("This is info message!");
        logger.warn("This is a warn message!");
        logger.error("This is error message!");

        try{
            System.out.println(5/0);
        }catch(Exception e){
            logger.error(e);
        }
    }
}

4-4) 运行结果

[DEBUG] 2017-03-29 12:56:00,454 method:org.genesis.arena.elk.ElkLog4jTest.main(ElkLog4jTest.java:11)
This is a debug message!
[INFO ] 2017-03-29 12:56:00,529 method:org.genesis.arena.elk.ElkLog4jTest.main(ElkLog4jTest.java:12)
This is info message!
[WARN ] 2017-03-29 12:56:00,531 method:org.genesis.arena.elk.ElkLog4jTest.main(ElkLog4jTest.java:13)
This is a warn message!
[ERROR] 2017-03-29 12:56:00,533 method:org.genesis.arena.elk.ElkLog4jTest.main(ElkLog4jTest.java:14)
This is error message!
[ERROR] 2017-03-29 12:56:00,538 method:org.genesis.arena.elk.ElkLog4jTest.main(ElkLog4jTest.java:19)
java.lang.ArithmeticException: / by zero

然后会在Logstash控制台看到输出如下图:

 

5. 连通Kibana

5-1) 打开 http://localhost:5601/

5-2) 创建索引

   还记得我们之前在logstash配置文件中配置的索引吗?

   log4j-%{+YYYY.MM.dd}

  因此,我们应该创建索引为:log4j-*

5-3)验证

 

 

从这里可以看到自己刚才在Java代码中记录的日志。

好了,一切大功告成了!!!

是不是很有成就感啊?

 

  

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享: