Last Updated: March 19, 2019
·
30.69K
· skck

How to use Logstash with Monolog

Monolog established as one of the most widely used PHP-Logger Library. There are dozens of different Handler to push Log Messages to, but I couldn’t find a simple tutorial how to use Monolog with Logstash.

Logstash is an open-source Log-Management tool that comes with a nice Interface, Kibana. I’m not going to describe how to install Logstash, since the documentation on the website is quite good.

Step 1: Setup Logstash

We’ll using Redis as the Logstash Input and Elasticsearch as the Output. Add the following to your Logstash config:

input {
  redis {
    key => phplogs
    data_type => ['list']
  }
}
output {
  elasticsearch_http {
    host => localhost
  }
}

Save the file and start the required services - Redis, Elasticsearch and Logstash. Don’t forget to add ’ — web’ as an argument when you’re starting the logstash agent, so Kibana will be available.

Step 2: Setup Monolog

Now that Logstash is running, let’s get into some coding. You’ll need to install monolog/monolog and predis/predis with composer.

<?php
// Be sure Monolog is installed via composer
require 'vendor/autoload.php'

use Monolog\Logger;
use Monolog\Handler\RedisHandler;
use Monolog\Formatter\LogstashFormatter;
use Predis\Client;

// Init a RedisHandler with a LogstashFormatter.
// The parameters may differ depending on your configuration of Redis.
// Important: The parameter 'logs' must be equal to the key you defined
// in your logstash configuration.
$redisHandler = new RedisHandler(new Client(), 'phplogs');
$formatter = new LogstashFormatter('my_app');
$redisHandler->setFormatter($formatter);

// Create a Logger instance with the RedisHandler
$logger = new Logger('logstash_test', array($redisHandler));

// Now you can start logging
$logger->info('Logging some infos to logstash.');

If you set up everything correctly, Monolog is sending the log message to Redis. Since Logstash is configured to listen to Redis, it will fetch the Message and send it to Elasticsearch. Open http://yourserver.tld:9292 and you should see the log message in Kibana.

1 Response
Add your response

Semicolon is missing after require 'vendor/autoload.php'

over 1 year ago ·