PHP code example of jakubkratina / elasticlog

1. Go to this page and download the library: Download jakubkratina/elasticlog library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jakubkratina / elasticlog example snippets


$app->bind(
    \JK\Elasticlog\Contracts\Elasticsearch\Client::class,
    function () {
        if (env('ELASTIC_ENABLED', false) === true) {
            return new \JK\Elasticlog\Elasticsearch\Client(
                \Elasticsearch\ClientBuilder::create()->setHosts([env('ELASTIC_HOST_PORT')])->build(),
                env('ELASTIC_INDEX')
            );
        }

        return new \JK\Elasticlog\Elasticsearch\NullClient();
    }
);

use JK\Elasticlog\Contracts\Elasticsearch\Client;
use JK\Elasticlog\Elasticsearch\Client as ElasticClient;
use JK\Elasticlog\Elasticsearch\NullClient;
use Elasticsearch\ClientBuilder;

final class ClientFactory
{
    /**
     * @return Client
     */
    public static function create(): Client
    {
        return self::isElasticsearchEnabled()
            ? self::createElasticClient()
            : self::createNullClient();
    }

    /**
     * @return Client
     */
    private static function createNullClient(): Client
    {
        return new NullClient();
    }

    /**
     * @return Client
     */
    private static function createElasticClient(): Client
    {
        return new ElasticClient(
            ClientBuilder::create()->setHosts([getenv('ELASTIC_HOST_PORT')])->build(), getenv('ELASTIC_INDEX')
        );
    }

    /**
     * @return bool
     */
    private static function isElasticsearchEnabled(): bool
    {
        return getenv('ELASTIC_ENABLED') === 'true';
    }
}

class MyCustomMessage extends \JK\Elasticlog\Log\Message
{
    public function toArray(): array
    {
        return [
            'foo' => 'bar'
        ];
    }
}

class MyCustomMessage extends \JK\Elasticlog\Log\Message
{
    private $name;
    
    public function __construct(string $name)
    {
        $this->name = $name;
    }
    
    public function toArray(): array
    {
        return [
            'foo' => 'bar',
            'name' => ucfirst($this->name)
        ];
    }
}

$message = new MyCustomMessage();

// ... your code

$logger->log($message); 

$message = (new Messages)->fooBarMessage();
$message->toArray(); // ['foo' => 'bar']

$message->add('a', (new Messages)->fooBarMessage());
$message->add('b', (new Messages)->barBazMessage());

$message->append((new Messages)->fooBarMessage());
$message->append((new Messages)->barBazMessage());

$message->merge([
    'x' => 'y',
]);

$this->assertEquals([
    'foo' => 'bar',
    'a'   => [
        'foo' => 'bar',
    ],
    'b'   => [
        'bar' => 'baz',
    ],
    'bar' => 'baz',
    'x'   => 'y',
], $message->build());