Skip to content

Instantly share code, notes, and snippets.

@DannyvdSluijs
Last active March 30, 2020 19:35
Show Gist options
  • Select an option

  • Save DannyvdSluijs/7a85cb5b4eb90fd573b0f96ee825451f to your computer and use it in GitHub Desktop.

Select an option

Save DannyvdSluijs/7a85cb5b4eb90fd573b0f96ee825451f to your computer and use it in GitHub Desktop.
An laravel console command testing the ability and performance of directly logging to ElasticSearch instead of to file and using filebeat to push into ES.
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Monolog\{ Logger, Processor, Handler};
class ElasticSearchLogCommand extends Command
{
/** @var string */
protected $signature = 'app:log-it';
/** @var string */
protected $description = 'Log the darn thing';
public function handle(): void
{
// Create the logger and some processors
$logger = new Logger('php-elastic-logging');
$logger->pushProcessor(new Processor\UidProcessor())
->pushProcessor(new Processor\HostnameProcessor())
->pushProcessor(new Processor\MemoryUsageProcessor());
// Prepare the ElasticSearch handler
$client = \Elasticsearch\ClientBuilder::create()
->setHosts(['https://***********:9243'])
->setBasicAuthentication('*********', '*******')
->build();
$elasticSearchHandler = new Handler\ElasticsearchHandler($client);
// A generic stream handler (old-style) logging
$streamHandler = new Handler\StreamHandler(base_path('application.log'));
// Push the handlers: A buffering handler (to avoid individual calls to ES) wrapping a fallback handler with
// Elastic Search as the primary handler and and plain old stream handler as the fallback when Elastic Search
// cannot be reached
$logger->pushHandler(new Handler\BufferHandler(new Handler\FallbackGroupHandler([$elasticSearchHandler, $streamHandler])));
// Some basic logging
$logger->debug('Log the darn thing', ['class' => __CLASS__, 'method' => __METHOD__]);
$logger->info('A random message', ['class' => __CLASS__, 'method' => __METHOD__]);
for ($x = 0; $x <= 100; $x++) {
$logger->notice('It is about to go down', ['class' => __CLASS__, 'method' => __METHOD__]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment