美文网首页PHP经验分享
CentOS 7.2从零搭建ELK

CentOS 7.2从零搭建ELK

作者: oraoto | 来源:发表于2016-12-17 20:55 被阅读821次

安装EPEL

sudo yum -y install epel-release

安装Redis

sudo yum -y install redis

设置开机自启动然后启动:

sudo systemctl daemon-reload
sudo systemctl enable redis.service
sudo systemctl start redis.service

安装ELK

只安装ELK:Elasticsearch、Logstash、Kibana,Elastic Stack的其他组件没装。

sudo rpm --import https://artifacts.elastic.co/GPG-KEY-elasticsearch

新增文件/etc/yum.repos.d/elasticsearch.repo

[elasticsearch-5.x]
name=Elasticsearch repository for 5.x packages
baseurl=https://mirrors.tuna.tsinghua.edu.cn/elasticstack/5.x/yum
gpgcheck=1
gpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch
enabled=1
autorefresh=1
type=rpm-md

用的是清华的源。

安装:

sudo yum -y install elasticsearch kibana logstash

Systemd开启开机自启动:

sudo systemctl daemon-reload
sudo systemctl enable elasticsearch.service
sudo systemctl enable kibana.service

启动:

sudo systemctl start elasticsearch.service
sudo systemctl start kibana.service
sudo systemctl start logstash.service

验证一下Elasticsearch:

curl http://localhost:9200
{
  "name" : "Nv3NQKr",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "Rx24DAWoS_ySLqeDCPNm0g",
  "version" : {
    "number" : "5.1.1",
    "build_hash" : "5395e21",
    "build_date" : "2016-12-06T12:36:15.409Z",
    "build_snapshot" : false,
    "lucene_version" : "6.3.0"
  },
  "tagline" : "You Know, for Search"
}

Elasticsearch和Kibana基本是开箱即用,默认配置就能跑起来。

配置LogStash

增加配置文件/etc/logstash/conf.d/logstash_indexer.conf:

input {
  redis {
    key => "logstash:phplogs"
    data_type => ["list"]
  }
}

output {
  elasticsearch {
    hosts => ["localhost:9200"]
  }
}

意思是从本机redis的logstash:phplogs里列表里读数据,写入本机的Elasticsearch。改完配置重新启动LogStash

Laravel写日志

写日志方法多样,我这里把日志写到Redis,让LogStash收集。

Laravel文档说在bootstrap/app.php配置Monolog,但是这个时候各种Service都没起来,难道要自己在这里连Redis?所以我用一个Service Provider配置Monolog:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Log;
use Monolog\Logger;
use Monolog\Handler\RedisHandler;
use Monolog\Formatter\LogstashFormatter;
use Redis;
use Config;

class LogServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $monolog      = Log::getMonolog();
        $formatter    = new LogstashFormatter(Config::get('app.name'));
        $redisHandler = new RedisHandler(Redis::connection('log'), 'logstash:phplogs');
        $redisHandler->setFormatter($formatter);
        $monolog->pushHandler($redisHandler);
    }

    public function register()
    {
        //
    }
}

Kibana

有日志写入后,就可在Kibana看到:

Kibana

参考

  1. Elasticsearch、Logstash、Kibana搭建统一日志分析平台
    内容有点旧。用两个服务器部署,其中一台有完整的ELK,另一台有LogStash收集日志,流程是LogStash收集日志文件 -> Redis -> LogStash -> ElasticSearch。
  2. How to use Logstash with Monolog
    参考了Redis和Monolog配置。

相关文章

网友评论

    本文标题:CentOS 7.2从零搭建ELK

    本文链接:https://www.haomeiwen.com/subject/becamttx.html