Download the PHP package nabafzar/laravel-log-center without Composer
On this page you can find all versions of the php package nabafzar/laravel-log-center. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download nabafzar/laravel-log-center
More information about nabafzar/laravel-log-center
Files in nabafzar/laravel-log-center
Package laravel-log-center
Short Description Unified logging, multi-channel notifications, and built-in log viewer for Laravel.
License MIT
Homepage https://github.com/saMahmoudzadeh/laravel-log-center
Informations about the package laravel-log-center
Laravel Log Center
Route every Laravel log event to Telegram, Bale, Mattermost, or any HTTP endpoint — with secret masking, async queuing, fallback transport, alert suppression, payload enrichment, a built-in log viewer, and an HTTP ingress for external services.
Features
- 🚚 Multiple transports — Telegram (with forum topics), Bale, Mattermost, generic webhook, and a null sink.
- 🎭 Per-transport formatters — plain, JSON, Markdown, Telegram HTML, Bale Markdown.
- 🔒 Secret masking — keys and in-message patterns are masked before formatting, queuing, or sending.
- ⚡ Async dispatch — push delivery onto a queue so logging never blocks a request.
- 🛟 Fallback transport — automatically retry through a second driver when the primary fails.
- 🔕 Alert suppression — collapse duplicate errors within a TTL window to stop notification floods.
- 📊 Daily / weekly digest — a summary of entry counts and the top issues, sent through your driver.
- 🧩 Payload enrichment — attach git SHA, hostname, or any context to every log.
- 🧭 Attribute routing —
#[LogTopic]routes a controller's logs to a specific Telegram thread. - 👀 Built-in log viewer — read-only viewer with search, live tail, and downloads.
- 📥 Incoming ingress — accept structured logs from other apps over HTTP.
Why Log Center?
Built on Monolog, not instead of it
Log Center does not replace Laravel's logging — it plugs into it. The integration point is a
standard Monolog handler (LogCenterHandler) that you register
on a normal logging channel, exactly like any other handler:
So every Log::error(), every Monolog processor, every channel and stack you already use keeps
working unchanged. Monolog stays the logging engine; Log Center is what happens after a record
is emitted — turning that single record into masked, formatted, routed, deduplicated delivery
across one or more providers.
Why not just use Monolog's own transport handlers?
Monolog ships a TelegramBotHandler, and there are community handlers for other services. They
are perfectly fine when all you need is "write this record to one chat." The reason this package
exists is that a raw handler is a sink — it takes a LogRecord and writes it to one
destination — whereas real alerting needs a pipeline. Stack several Monolog handlers together
and you end up re-implementing masking, queuing, fallback, and deduplication in each one, with no
shared contract between providers. Log Center makes that pipeline the product:
| Concern | Raw Monolog handler | Log Center |
|---|---|---|
| Context | Whatever is in the record | Lifts exception, request, and authenticated user into a typed LogPayload |
| Secrets | Sent as-is | Masked by key and message pattern before formatting/queue/send |
| Formatting | Baked into the handler | Swappable LogFormatterInterface per transport |
| Delivery cost | On the request thread | Optional queue dispatch with retry + backoff |
| Resilience | Fails silently | Fallback driver, LogDispatchFailed event, recursion-safe error handling |
| Noise | Every duplicate sent | Fingerprint-based suppression with occurrence counts |
| Routing | One channel | #[LogTopic] → Telegram forum thread / #hashtag on other drivers |
| Iranian platforms | Not covered | First-class Bale support |
Rule of thumb: if you need "ship this record to one chat," a Monolog handler is enough. If you need masking, async delivery, fallback, deduplication, and routing as one contract across several providers, that is what this package adds on top of Monolog.
Table of Contents
- Requirements
- Installation
- Quick Start
- How It Works
- Drivers
- Formatters
- Queue Dispatch
- Fallback Transport
- Failure Channel
- Alert Suppression
- Log Digest
- Secret Masking
- Payload Enrichment
- Events
- Log Topic Attribute
- Log Viewer
- Incoming Log Ingress
- Custom Transports
- Custom Formatters
- Testing Your App
- Testing
Requirements
| Requirement | Supported |
|---|---|
| PHP | 8.2, 8.3, 8.4 (Laravel 13 needs 8.3+) |
| Laravel | 10, 11, 12, 13 |
| Monolog | 3.x |
Installation
The service provider is auto-discovered. Publish the configuration file:
Quick Start
Add a channel to config/logging.php:
A record is sent only when it meets both the channel level and LOGCENTER_LEVEL (default error),
so a channel left at Laravel's default debug level still sends errors and above only. Set
LOGCENTER_LEVEL=debug to let the channel level decide on its own.
Set it as your log channel and configure a transport driver:
Or stack it alongside an existing channel so file logging keeps working:
Every Log::error(), Log::critical(), or uncaught exception now lands in your configured
transport. Verify your setup without triggering a real error:
logcenter:check lists each part of the setup as OK, WARN, FAIL or SKIP and exits with code
1 when something is broken, so it also fits a deploy pipeline. It checks that Log Center is attached
to a log channel, the level, the default and fallback drivers and their formatters, and the
credentials: Telegram and Bale tokens with getMe and chat access with getChat, a Mattermost bot
token with /users/me — read-only calls that never post a message. Webhook URLs are only validated,
because checking one would mean posting to it. It also checks the queue connection, the suppression
cache, the failure channel, the viewer gate and the incoming token.
How It Works
Masking runs before formatting and before the payload is serialized onto a queue, so unmasked secrets never reach queue storage, transport metadata, or error logs.
Drivers
Telegram
Delivers messages via the Telegram Bot API. Supports forum topics, message splitting, and per-level routing.
Per-level forum topics — route different log levels to different threads:
Tag-to-topic routing — map #[LogTopic] tag names to thread IDs (takes priority over topics_level):
Message splitting — split long messages instead of truncating:
Bale
Delivers via the Bale messenger Bot API — the Iranian messaging platform.
Mattermost
Supports two modes: incoming webhook and bot API.
Webhook
Sends a structured payload to any HTTP endpoint.
Custom headers:
Null
Discards all messages silently. Useful as the default driver in local or testing environments.
Formatters
| Name | Best for | Description |
|---|---|---|
plain |
Webhook, generic | Plain text |
markdown |
Mattermost, generic | GitHub-flavoured Markdown |
json |
Log aggregators | Structured JSON object |
telegram_html |
Telegram | HTML with Telegram entity support |
bale_markdown |
Bale | Markdown formatted for Bale |
Each driver defaults to a sensible formatter (Telegram → telegram_html, Bale → bale_markdown,
Mattermost → markdown). Override globally or per driver:
Queue Dispatch
Dispatch log jobs asynchronously so transport delivery never blocks a request:
Failed jobs are retried with exponential backoff: 10 s → 60 s → 300 s. Permanent failures
fire a LogDispatchFailed event.
Masking runs before the job is pushed to the queue — sensitive data never enters queue storage.
Use the queue in production. Without it, logs are sent during the request that wrote them. That costs nothing while the destination is healthy, but if it accepts the connection and then stops answering, every request that logs an error waits for the driver timeout (5 s by default) before the user gets a response — plus the same again when a fallback driver is configured. If you send synchronously, keep the timeouts short (
LOGCENTER_TELEGRAM_TIMEOUT,LOGCENTER_BALE_TIMEOUT,LOGCENTER_MATTERMOST_TIMEOUT,LOGCENTER_WEBHOOK_TIMEOUT).
Fallback Transport
When the primary driver fails, a fallback driver is tried automatically:
The fallback must differ from the primary driver. Any failed send triggers it — a timeout, HTTP 429 or 5xx, and also a configuration error such as a wrong token (4xx) — so the alert still gets out.
Failure Channel
Log Center never interrupts your app: if it cannot deliver a log, or something fails inside the package, the request carries on. To keep a record of those problems in your own log files, name a Laravel log channel:
It then writes a warning there for every log that could not be delivered after the fallback and all queue retries, and for errors inside the package:
Secrets in the error text (bot tokens, webhook URLs) are already masked. Without the setting, the same
messages go to PHP's error_log. The original log itself is written by your other channels as usual,
for example single in LOG_STACK=single,logcenter.
Alert Suppression
Prevent notification floods by suppressing repeated identical logs within a time window:
The first occurrence is delivered normally. Duplicates within the TTL window fire a
LogSuppressed event with an $occurrences counter instead of re-sending.
Production note: suppression and its occurrence counter are backed by the configured cache store. In a multi-worker deployment, point
LOGCENTER_SUPPRESSION_STOREat a shared, atomic store such as Redis. With per-process stores (e.g.array), each worker tracks its own counts and suppression will not be global.
Log Digest
A summary of the last day or week, sent through your driver like any other log: entry counts per level and the most
frequent issues, with new ones marked [NEW].
Run it by hand, or let Log Center add it to Laravel's scheduler:
How it works:
- The counts come from the log files in
viewer.paths(the viewer does not have to be enabled), grouped exactly like the viewer groups issues. Write your logs to a file channel (singleordaily) alongsidelogcenter. - An issue is
[NEW]when it does not appear before the period in the files still kept. - The digest is sent as an
infolog on thedigestchannel with the tagdigest, so masking, the fallback driver andLogCenter::fake()apply. On Telegram, map the tag to a forum topic with'tag_topics' => ['digest' => 1234]. - Files up to
LOGCENTER_DIGEST_MAX_FILE_SIZE(100 MB by default,0for no limit) are read, even when they are larger than the viewer's own limit. - On several servers, schedule the command yourself with
->onOneServer()instead ofLOGCENTER_DIGEST_ENABLED, so only one digest is sent.
Secret Masking
Sensitive values are masked before formatting, queue dispatch, and sending — including nested arrays and message string patterns.
Default masked keys: password, password_confirmation, token, access_token,
refresh_token, authorization, api_key, secret
A key is masked when its name contains one of these (case-insensitive by default), so password
also covers current_password and new_password, and token covers api_token and Laravel's
CSRF _token.
Payload Enrichment
Attach custom context to every log payload before masking and dispatch:
Enrichers run before secret masking, so any sensitive values added here are still masked.
Events
| Event | Fired when |
|---|---|
LogDispatched |
A log was delivered successfully |
LogDispatchFailed |
A delivery attempt failed (primary or fallback) |
LogSuppressed |
A duplicate log was suppressed within the TTL window |
Log Topic Attribute
Route logs to a specific Telegram topic thread and append a hashtag on every other driver by
decorating a method or class with #[LogTopic].
The resolver checks the active call stack and the current Laravel route action, so controller attributes still apply when an exception is logged after the action has unwound.
Multiple tags, class-level, or tag-only (no topic ID) are all supported. Topic resolution priority:
topicIdfrom the#[LogTopic]attributetag_topicsconfig (tag → topic ID)topics_levelconfig (level → topic ID)drivers.telegram.topic_idconfig default
Octane & queue workers: attribute resolution walks the live call stack and falls back to the current Laravel route action. In a queued job or long-running Octane worker where the decorated controller frame is gone and no route is bound, the
#[LogTopic]attribute will not resolve. Two alternatives:Option A — decorate the job's
handle()method:Option B — pass routing explicitly in the log context:
The attribute always takes priority. Context values are the fallback when no attribute is on the stack. Both
logcenter_topic_idandlogcenter_tagsare consumed and do not appear in the log payload's context.
Log Viewer
A read-only viewer for your Laravel log files, built to answer "what broke, where, and how often?" quickly.
Large logs stay fast: parsed entries are kept between requests in storage/framework/cache/logcenter,
and when a log grows only the new lines are read. A rotated or truncated file is parsed again from
the start. On a 4 MB log with 4,000 entries, a page load drops from about 190 ms to about 45 ms.
What you get:
- Issues, not lines — identical errors are grouped, with event count, first seen and last seen.
- Exception details — class, message and
file:lineparsed from Laravel's log format, plus a preview of the source lines around the error (PHP files inside your app only, and only whencode_snippetsis on). - Readable stack traces — your application frames are highlighted and vendor frames are folded. "Caused by" chains for previous exceptions are shown too.
- Context, occurrences and raw tabs — highlighted JSON context, every occurrence with its raw entry, and the latest raw entry with a copy button.
- Copy for AI — "Copy stack trace" copies the raw trace, and "Copy AI prompt" copies a ready-to-paste
prompt for ChatGPT, Claude or any other assistant: the exception, location, occurrence counts, source
lines, "Caused by" chain, stack trace and context. Secrets are masked with your
maskrules and your app's base path is removed from file paths. Nothing is sent anywhere; the text only goes to your clipboard. - Activity chart — errors, warnings and other entries over time, following your filters.
- Search and level filters — level chips keep their counts while you filter.
- Notification links — the "open in viewer" link in Telegram, Bale and Mattermost messages opens the exact error, already expanded.
- Live tail, download, dark mode, mobile layout and keyboard shortcuts (
/search,j/kmove,eexpand all,llive,ttheme,?help).
LOGCENTER_VIEWER_EDITOR turns file paths into "open in editor" links. A custom template can use
{file} and {line}, for example idea://open?file={file}&line={line}.
Who can open the viewer
The viewer exposes raw log contents, including stack traces and request data, so being logged in is
not enough. Access is decided by the viewLogCenter gate. Until you define it, the viewer is only
available in the local environment and returns 403 everywhere else.
Define the gate in a service provider's boot() method, for example AppServiceProvider:
The gate runs after the auth middleware (enabled by default with LOGCENTER_VIEWER_AUTH_ENABLED),
so guests are redirected to log in first. If your app has no login route (an API-only app, for
example), guests get a 401 instead of an error. Inside a directory listed in viewer.paths, only *.log
files can be opened, downloaded or tailed.
Live Tail — click the Live button to stream new entries in real time via SSE (falls back to polling automatically).
For non-browser consumers:
Incoming Log Ingress
Accept structured log payloads from external applications and dispatch them through the configured transport:
Rate-limited to 60 requests per minute by default. Override via config/logcenter.php:
Custom Transports
1. Create the transport class — suggested path: app/Logging/DiscordTransport.php
2. Register the driver in AppServiceProvider::boot():
3. Add config to config/services.php:
4. Activate it:
supportsTopics() reference
| Return value | Behaviour when #[LogTopic] is present |
|---|---|
false (default) |
Tag appended as #payments in the message body |
true |
Transport receives $payload->tags and is responsible for routing to the correct sub-channel/thread |
Built-in transports: TelegramTransport returns true (routes to forum topic threads); all
others return false.
Custom Formatters
A formatter turns a log into the text a transport sends. Write your own when the built-in ones do not fit, for example to send JSON in the shape your webhook expects.
1. Create the formatter by implementing LogFormatterInterface:
The payload is already masked when it reaches the formatter, so secrets stay hidden.
2. Register it in AppServiceProvider::boot():
The resolver receives the container. Registering a built-in name (plain, json, markdown,
telegram_html, bale_markdown) replaces that formatter. Names are case-insensitive.
3. Use it globally or for one driver:
Or per driver in config/logcenter.php: 'drivers' => ['webhook' => ['formatter' => 'opsgenie', ...]].
Testing Your App
LogCenter::fake() records what would be sent instead of sending it, so you can test your own
alerts. The rest of the pipeline still runs — level filter, masking, formatter, #[LogTopic] routing,
suppression and fallback — and delivery becomes synchronous, so it works with the queue enabled.
| Method | Checks |
|---|---|
assertSent(?callable) |
at least one log was sent (matching the callback) |
assertSentTo($driver, ?callable) |
a log was sent to that driver |
assertNotSent(callable) |
no sent log matches the callback |
assertSentCount($n) / assertNothingSent() |
how many logs were sent |
sent(?callable) |
the recorded logs (driver, payload, message) for your own assertions |
Callbacks receive the masked LogPayload, the FormattedMessage the driver's formatter produced,
and the driver name. To test the fallback driver or LogDispatchFailed listeners, make a driver
fail: LogCenter::fake()->failing('telegram').
Testing
All transport tests use Laravel's Http::fake() — no real network calls are made.
Changelog
Please see CHANGELOG for details on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
- Sayyed Abdollah Mahmoudzadeh
- All Contributors
License
The MIT License (MIT). Please see License File for more information.
All versions of laravel-log-center with dependencies
guzzlehttp/guzzle Version ^7.5|^8.0
laravel/framework Version ^10.0|^11.0|^12.0|^13.0
monolog/monolog Version ^3.0