PHP code example of nabafzar / laravel-log-center

1. Go to this page and download the library: Download nabafzar/laravel-log-center 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/ */

    

nabafzar / laravel-log-center example snippets


// One channel. Errors land in Telegram, secrets masked, off the request path.
Log::error('Payment gateway timeout', ['order_id' => 'ORD-999']);

'logcenter' => [
    'driver'  => 'monolog',
    'handler' => \Nabafzar\LogCenter\Logging\LogCenterHandler::class,
],

'channels' => [
    'logcenter' => [
        'driver'  => 'monolog',
        'handler' => \Nabafzar\LogCenter\Logging\LogCenterHandler::class,
        'with'    => ['level' => env('LOG_LEVEL', 'error')],
    ],
],

// config/logcenter.php
'drivers' => [
    'telegram' => [
        'topics_level' => [
            'critical' => 1001,
            'error'    => 1002,
            'warning'  => 1003,
        ],
    ],
],

'drivers' => [
    'telegram' => [
        'tag_topics' => [
            'payments' => 1010,
            'checkout' => 1011,
        ],
    ],
],

'drivers' => [
    'webhook' => [
        'headers' => ['Authorization' => 'Bearer your-token'],
    ],
],

'mask' => [
    'keys'           => ['password', 'token', 'stripe_key'],
    'replacement'    => '******',
    'case_sensitive' => false,
],

use Nabafzar\LogCenter\Contracts\PayloadEnricherInterface;
use Nabafzar\LogCenter\DTO\LogPayload;
use Nabafzar\LogCenter\Processors\PayloadProcessor;

// In AppServiceProvider::boot()
$this->app->make(PayloadProcessor::class)
    ->addEnricher(new class implements PayloadEnricherInterface {
        public function enrich(LogPayload $payload): LogPayload
        {
            $data = (array) $payload;
            $data['extra'] = array_merge($payload->extra, [
                'git_sha'     => config('app.git_sha'),
                'server_name' => gethostname(),
            ]);

            return new LogPayload(...$data);
        }
    });

use Nabafzar\LogCenter\Events\LogDispatched;
use Nabafzar\LogCenter\Events\LogDispatchFailed;
use Nabafzar\LogCenter\Events\LogSuppressed;

Event::listen(LogDispatched::class, function (LogDispatched $event): void {
    // $event->payload  — the LogPayload that was sent
    // $event->result   — the TransportResult
});

Event::listen(LogSuppressed::class, function (LogSuppressed $event): void {
    // $event->occurrences — suppression count for this fingerprint
});

Event::listen(LogDispatchFailed::class, function (LogDispatchFailed $event): void {
    // $event->retryable         — whether the queue will retry
    // $event->result->errorMessage
});

use Nabafzar\LogCenter\Attributes\LogTopic;

#[LogTopic(tag: 'payments', topicId: 1234)]
public function charge(ChargeRequest $request): JsonResponse
{
    // Telegram  → routed to forum topic 1234
    // All others → "#payments" appended to message
}

> #[LogTopic(tag: 'payments', topicId: 1234)]
> public function handle(): void { ... }
> 

> Log::error('Payment job failed', [
>     'logcenter_topic_id' => 1234,
>     'logcenter_tags'     => ['payments'],
>     'order_id'           => 'ORD-999',
> ]);
> 

use Illuminate\Support\Facades\Gate;

Gate::define('viewLogCenter', function ($user) {
    return in_array($user->email, [
        '[email protected]',
    ]);
});

'incoming' => [
    'middleware' => ['api', 'throttle:120,1'],
],



namespace App\Logging;

use Illuminate\Support\Facades\Http;
use Nabafzar\LogCenter\Contracts\LogTransportInterface;
use Nabafzar\LogCenter\DTO\FormattedMessage;
use Nabafzar\LogCenter\DTO\LogPayload;
use Nabafzar\LogCenter\DTO\TransportResult;
use Nabafzar\LogCenter\Enums\MessageFormatEnum;

final class DiscordTransport implements LogTransportInterface
{
    public function __construct(
        private readonly string $webhookUrl,
        private readonly int $timeout,
    ) {}

    public function send(LogPayload $payload, FormattedMessage $message): TransportResult
    {
        $response = Http::timeout($this->timeout)
            ->post($this->webhookUrl, ['content' => $message->content]);

        return $response->successful()
            ? TransportResult::success('discord', statusCode: $response->status())
            : TransportResult::failed('discord', errorMessage: $response->body(), statusCode: $response->status());
    }

    public function supportedFormats(): array
    {
        return [MessageFormatEnum::PLAIN, MessageFormatEnum::MARKDOWN];
    }

    public function supportsTopics(): bool
    {
        // Return true only if your transport can route messages to
        // sub-channels / threads based on #[LogTopic] tag names.
        // Either way, the built-in formatters render tags as "#hashtags" in the message body.
        return false;
    }
}

use App\Logging\DiscordTransport;
use Nabafzar\LogCenter\Factories\TransportFactory;

$this->app->resolving(TransportFactory::class, function (TransportFactory $factory, $app): void {
    $factory->extend('discord', fn () => new DiscordTransport(
        webhookUrl: config('services.discord.webhook_url'),
        timeout:    config('services.discord.timeout', 5),
    ));
});

'discord' => [
    'webhook_url' => env('DISCORD_WEBHOOK_URL'),
    'timeout'     => env('DISCORD_TIMEOUT', 5),
],

namespace App\Logging;

use Nabafzar\LogCenter\Contracts\LogFormatterInterface;
use Nabafzar\LogCenter\DTO\FormattedMessage;
use Nabafzar\LogCenter\DTO\LogPayload;

final class OpsgenieFormatter implements LogFormatterInterface
{
    public function format(LogPayload $payload): FormattedMessage
    {
        return new FormattedMessage(
            content: json_encode([
                'message'  => mb_substr($payload->message, 0, 130),
                'priority' => $payload->level === 'CRITICAL' ? 'P1' : 'P3',
                'details'  => $payload->context,
            ]),
            format: 'json',
        );
    }
}

use App\Logging\OpsgenieFormatter;
use Nabafzar\LogCenter\Factories\FormatterFactory;

$this->app->make(FormatterFactory::class)
    ->extend('opsgenie', fn ($app) => new OpsgenieFormatter);

use Nabafzar\LogCenter\DTO\FormattedMessage;
use Nabafzar\LogCenter\DTO\LogPayload;
use Nabafzar\LogCenter\Facades\LogCenter;

public function test_a_failed_payment_alerts_the_team(): void
{
    $fake = LogCenter::fake();

    $this->postJson('/checkout', ['card' => 'declined'])->assertStatus(402);

    $fake->assertSentTo('telegram', fn (LogPayload $payload, FormattedMessage $message) =>
        $payload->message === 'Payment failed' && $payload->context['order_id'] === 42
    );
}
bash
php artisan vendor:publish --tag=logcenter-config
dotenv
LOG_CHANNEL=stack
LOG_STACK=daily,logcenter
bash
php artisan logcenter:check --driver=bale   # check one driver
php artisan logcenter:check --offline       # skip calls to the providers
dotenv
LOGCENTER_FORMATTER=telegram_html          # global default
LOGCENTER_TELEGRAM_FORMATTER=telegram_html # per driver
bash
php artisan logcenter:digest                      # last 24 hours
php artisan logcenter:digest --period=weekly      # last 7 days
php artisan logcenter:digest --since="48 hours ago" --level=error
php artisan logcenter:digest --driver=mattermost  # another driver for this run
php artisan logcenter:digest --dry-run            # print it, send nothing