Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Gelf Php Laravel Package

mlehner/gelf-php

mlehner/gelf-php is a PHP library for sending GELF (Graylog Extended Log Format) messages to Graylog over UDP or TCP, with chunked message support, publishers, transports, and a PSR-3 logger for structured application logging.

Deep Wiki
Context7

Getting Started

Install via Composer and let it pull in the PSR autoloader:

composer require mlehner/gelf-php

There is no framework integration, config file, or service provider to publish — this is a small, single-purpose library. The three objects you touch are Gelf\Message, Gelf\Publisher, and a transport (Gelf\Transport\UdpTransport, Gelf\Transport\TcpTransport, or Gelf\Transport\StreamSocketClient). Look first at src/Gelf/Message.php for the setters and level constants, then src/Gelf/Publisher.php to see that publish() simply encodes the message and hands bytes to the transport.

The minimal first use case — ship one GELF message to a local Graylog input:

require 'vendor/autoload.php';

use Gelf\Message;
use Gelf\Publisher;
use Gelf\Transport\UdpTransport;

$transport = new UdpTransport('127.0.0.1', 12201);
$publisher = new Publisher($transport);

$message = new Message();
$message->setHost(gethostname());
$message->setShortMessage('Deploy finished');
$message->setLevel(Message::LEVEL_INFO);
$message->setFacility('deploy');
$message->setAdditional('release', '2024.06.1');

$publisher->publish($message);

Verify it landed in Graylog's System → Inputs → Show received messages (or watch the input's traffic counter). Once you see that one line, move on to wrapping the publisher in a reusable logger.

Implementation Patterns

Reuse the publisher, not the transport. Construct the transport and publisher once per process (a container singleton or static holder) and pass Message objects to it. Opening a new UDP socket per log line is wasteful and can exhaust file descriptors in long-running workers.

Monolog handler is the shortest path. If the app already uses Monolog, Monolog\Handler\GelfHandler accepts a Publisher directly, so you get levels, context, and exception formatting for free:

$logger = new Monolog\Logger('app');
$logger->pushHandler(new Monolog\Handler\GelfHandler($publisher));
$logger->error('Payment failed', ['order_id' => 42]);

Exception logging. GELF separates short_message (the Graylog list column) from full_message (the detail pane). Use both:

$message->setShortMessage(get_class($e) . ': ' . $e->getMessage());
$message->setFullMessage((string) $e);
$message->setAdditional('exception_class', get_class($e));
$message->setFile($e->getFile());
$message->setLine($e->getLine());

Structured context. Put request IDs, tenant IDs, user IDs, and durations in setAdditional(). They become searchable fields in Graylog, which is the whole point of using GELF over plain syslog. Keep values as strings, numbers, or booleans — nested arrays are not part of GELF 1.1.

Transport trade-offs:

  • UdpTransport — fire-and-forget, lowest latency, but silently drops on network congestion or oversized packets. Fine for high-volume debug logging.
  • TcpTransport / StreamSocketClient — reliable delivery and connection reuse, but you must handle exceptions when Graylog is down. Better for audit-relevant messages.

Facade / DI wiring in Laravel. Bind a singleton in a service provider:

$this->app->singleton(Publisher::class, function () {
    return new Publisher(new UdpTransport(
        config('graylog.host', '127.0.0.1'),
        config('graylog.port', 12201)
    ));
});

Then inject Publisher wherever you need it, or attach a Monolog GelfHandler in config/logging.php via a custom channel.

Testing. Gelf\Transport\TransportInterface has a single send() method. Implement an in-memory fake transport and assert on encoded payloads instead of hitting a real Graylog instance:

class FakeTransport implements Gelf\Transport\TransportInterface {
    public array $sent = [];
    public function send($data) { $this->sent[] = $data; return strlen($data); }
    // also implement getEndpoint() if your version's interface requires it
}

Gotchas and Tips

Set host explicitly. GELF 1.1 requires it, and older versions of this library do not default it to gethostname(). A missing host causes Graylog to reject the message with no error at the sender.

Reserved field names throw. Message rejects additional fields that collide with GELF keys (id, host, short_message, full_message, timestamp, level, facility, file, line, version) via InvalidArgumentException. Pass keys without the leading underscore; don't hand-prefix _foo yourself unless your version documents it — the encoder handles GELF conventions.

UDP size limit is ~8 KB. Large full_message bodies (stack traces with long arguments) get silently truncated or dropped. Either truncate before sending or switch to TCP for exception-heavy logging.

Never let logging break the request. Wrap TCP publishes in try/catch and swallow transport exceptions; a Graylog outage should not 500 your app. UDP sends rarely throw but can still fail at the socket layer.

Levels are syslog integers. Use the Message::LEVEL_* constants (0 = emergency through 7 = debug). If you pass your own strings, Graylog will bucket them under "unknown". Map Monolog levels rather than reinventing them.

setTimestamp() accepts floats and DateTime. The encoder writes a numeric Unix timestamp with fractional seconds. If you need event time rather than receive time (e.g. replaying logs), set it explicitly.

Silent drops are the #1 debugging pain. If messages don't appear: confirm the Graylog input type matches your transport (UDP vs TCP), confirm the bind address (0.0.0.0 vs 127.0.0.1 in Docker), and listen manually with nc -ul 12201. Graylog's input metrics panel shows received vs. parsed counts — a mismatch usually means a malformed field.

This package is frozen at 2014. No releases since, and the code predates modern PHP versions — expect deprecation notices on PHP 8 and potential visibility/signature issues. For new projects, prefer the actively maintained graylog2/gelf-php fork, which descends from this library and adds HTTP transport, gzip compression, and error-ignoring wrappers. Migration is mostly a namespace/composer-name change.

Extension points are thin by design. The only meaningful customization hooks are a custom TransportInterface implementation (for batching, retries, or routing to multiple Graylog nodes) and a custom encoder if you need to alter the JSON. There is no plugin system, so keep enhancements in your own decorator classes rather than forking.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
pharaonic/laravel-notification-dependencies
beautinow/translug
dev-brainiac/bot-cloaked
octoberrain/html
octoberrain/extension
octoberrain/exception
octoberrain/contracts
frankyso/ipaymu
3mdikram/worldmoneywords
snowsoft/config
itmosoft/laravel-subscriptions
larva/laravel-ai-qwen
adachsoft/api-version-bundle
cgv/localized-resource
noith/settings
kda/laravel-package
kda/filament-dynamic-navigation
bypersoft/signbox
pairus/product-data
fayne/laravel-filament-cms-core