PHP code example of giacomofurlan / php-graylog-gelf

1. Go to this page and download the library: Download giacomofurlan/php-graylog-gelf 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/ */

    

giacomofurlan / php-graylog-gelf example snippets



use GiacomoFurlan\Graylog\ExtendedGELFLogger;
use GiacomoFurlan\Graylog\GELF;
use GiacomoFurlan\Graylog\GELFException;
use GiacomoFurlan\Graylog\GELFLogger;
use GiacomoFurlan\Graylog\UDPWriter;
use Psr\Log\LogLevel;

// ...

$address = 'ip.or.dns.of.graylog.server';
$port = 12201; // or whatever port is configured in Graylog 2
$hostId = 'MyHost'; // host identifier

// Instantiate the writer
$writer = new UDPWriter($address, $port);
// Instantiate the logger (use one or the other... or both)
$simpleLogger = new GELFLogger($writer, $hostId);
$extendedLogger = new ExtendedGELFLogger($writer, $hostId);

// ...

// GELFLogger usage example
try {
  // ...
} catch (\Throwable $exception) {
    $simpleLogger->log(LogLevel::ERROR, $exception->getMessage(), ['code' => $exception->getCode()]);
    // or
    $simpleLogger->error($exception->getMessage(), ['code' => $exception->getCode()]);
}

// ExtendedGELFLogger usage example
try {
    // ...
} catch (\Throwable $exception) {
    $message = new GELF($exception->getMessage(), ['code' => $exception->getCode()]);
    
    $message->setHost('Overwritten host');
    $message->setFullMessage($exception->getTraceAsString());
    $message->setContextEntryset('fileName', $exception->getFile());
    $message->setContextEntryset('fileLine', $exception->getLine());
    
    $extendedLogger->gelfError($message);
}