整合日志到ES

2019-08-11  本文已影响0人  段义纬

1、elasticsearch的安装就跳过了,打开http://127.0.0.1:9200/如下,再继续

{
  "name": "PC-201902071414",
  "cluster_name": "elasticsearch",
  "cluster_uuid": "_lqn19mvSx-SwSeyRHwYvA",
  "version": {
    "number": "7.3.0",
    "build_flavor": "default",
    "build_type": "zip",
    "build_hash": "de777fa",
    "build_date": "2019-07-24T18:30:11.767338Z",
    "build_snapshot": false,
    "lucene_version": "8.1.0",
    "minimum_wire_compatibility_version": "6.8.0",
    "minimum_index_compatibility_version": "6.0.0-beta1"
  },
  "tagline": "You Know, for Search"
}

2、过程:
本来想自己写的,也找了很多博客,但是好像都是5.5版的Laravel,也不知道是否有效就不贴链接了;偶然发现monolog下有vendor/monolog/monolog/src/Monolog/Handler/ElasticSearchHandler.php,又发现实例化时需要Elastica\Client,所以先下包

sudo composer require ruflin/elastica

3、Talk is cheap:

ELASTIC_HOST=127.0.0.1:9200
ELASTIC_LOG_INDEX=blog
ELASTIC_LOG_TYPE=log
<?php
return [
    ……
    'es' => [
        'hosts' => [
            env('ELASTIC_HOST')
        ]
    ]
];
<?php
    ……
    'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['es'],
            'ignore_exceptions' => false,
        ],

        'es' => [
            'driver' => 'custom',
            'via' => App\Ship\Logging\ESLogger::class,
            'level' => 'debug',
            'index' => env('ELASTIC_LOG_INDEX', 'blog'),
            'type' => env('ELASTIC_LOG_TYPE', 'log'),
        ],
      ……
];
<?php


namespace App\Ship\Logging;


use Monolog\Logger;
use Monolog\Handler\ElasticSearchHandler;

class ESLogger
{
    /**
     * Create a custom Monolog instance.
     *
     * @param array $config
     * @return Logger
     */
    public function __invoke(array $config)
    {
        $client = app('es');
        $handler = new ElasticSearchHandler($client, $config);
        return new Logger('es', [$handler]);
    }
}
<?php

namespace App\Providers;

use Elastica\Client;
use Illuminate\Support\ServiceProvider;

class ESServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton('es', function () {
            return new Client(config('services.es'));
        });
    }

}
<?php
use Illuminate\Support\Facades\Route;

Route::get('/test/logging', function () {
    Illuminate\Support\Facades\Log::info(
        'ElasticSearch写入日志!',
        [
            'code' => 200,
            'msg' => '不错,成功了!',
            'data' => [
                'user' => 'TruckCoder'
            ]
        ]
    );

    $client = app('es');
    $query = '{"query":{"match":{"message":"写入日志"}}}';
    $index = $client->getIndex(config('logging.channels.es.index'));
    $type = $index->getType(config('logging.channels.es.type'));

    $path = $index->getName() . '/' . $type->getName() . '/_search';
    $response = $client->request($path, Elastica\Request::GET, $query);
    $responseArray = $response->getData();
    return $responseArray;
});

keyword:elasticsearch | log | laravel | 日志 | ES

上一篇下一篇

猜你喜欢

热点阅读