How to implement real-time log analysis with PHP and Elasticsearch
2.1 Install Elasticsearch
First, you need to install Elasticsearch. You can download and install the version suitable for your operating system from the Elasticsearch official website (https://www.elastic.co/downloads/elasticsearch). After the installation is complete, configure and start Elasticsearch.
2.2 Install PHP client
Next, we need to install PHP’s Elasticsearch client. Run the following command from the command line to install:
composer require elasticsearch/elasticsearch
Once completed, you are ready to use the Elasticsearch client in your PHP project.
The following is a sample code that uses PHP and Elasticsearch to implement real-time log analysis.
build(); // 创建一个index(如果不存在) $params = [ 'index' => 'logs' ]; if (!$client->indices()->exists($params)) { $client->indices()->create($params); } // 模拟生成日志 $log = [ 'level' => 'error', 'message' => 'There was an error in the application.', 'timestamp' => '2021-01-01T10:00:00' ]; // 将日志写入Elasticsearch $params = [ 'index' => 'logs', 'body' => $log ]; $client->index($params); // 实时查询最新日志 $params = [ 'index' => 'logs', 'body' => [ 'query' => [ 'match_all' => [] ], 'sort' => [ 'timestamp' => [ 'order' => 'desc' ] ] ] ]; $response = $client->search($params); // 打印最新日志 foreach ($response['hits']['hits'] as $hit) { echo $hit['_source']['message'] . PHP_EOL; } ?>
The logic of the above code is as follows:
The above is the detailed content of How to implement real-time log analysis with PHP and Elasticsearch. For more information, please follow other related articles on the PHP Chinese website!