F.FiachehrDocumentation
Laravel package / observability

Laravel Logger.

Privacy-first structured logging for Laravel, with a secure, searchable log explorer. Write bounded JSONL events, understand exceptions, correlate requests, and inspect what matters — without a database, external telemetry, or a frontend build step.

PHP 8.3–8.5Laravel 12 / 13Monolog 3MIT LicenseNo database required

Features

#

A practical logging toolkit designed to be safe by default and easy to integrate into existing Laravel applications.

{ }Structured JSONL logs

Compact, daily JSON files with predictable event fields and bounded file sizes.

◇Protected dashboard

Built-in, responsive explorer with filters, event details, request grouping and theme switching.

◎Privacy by default

Allowlisted metadata, categorical messages, sensitive-key filtering and sanitized exceptions.

↗Request correlation

Generated request IDs, route metadata and isolated context across requests and queue jobs.

▣Laravel-native integration

Custom Monolog channel, service provider auto-discovery and Artisan commands.

⌁No extra infrastructure

No migrations, external service, database tables, npm setup or telemetry collector.

Requirements

#
ComponentSupported
PHP8.3, 8.4, 8.5
Laravel12.x or 13.x
Monolog3.x
PHP extensionsjson, mbstring
StoragePrivate, writable local filesystem (POSIX-oriented)
Dashboard sessionsLaravel session and persistent cache drivers
Opt-in by design

Installing the package does not enable logging, change your application's default channel, capture HTTP requests, or expose the dashboard.

Installation

#

Install the package using Composer, register the structured channel, and explicitly enable the dashboard if you want the browser interface.

Install and publish configuration

Terminal
composer require fiachehr/laravel-logger:^0.2
php artisan log-explorer:install

The installer preserves an existing config file. For noninteractive publishing:

Terminal
php artisan vendor:publish --tag=log-explorer-config

Add the custom logging channel

In config/logging.php, add this entry under channels:

config/logging.php · PHP
'observability' => [
    'driver' => 'custom',
    'via' => \Fiachehr\LaravelLogger\Logging\CreateLogger::class,
    'level' => env('LOG_EXPLORER_LEVEL', 'debug'),
],

Enable structured logging with environment variables:

.env
LOG_EXPLORER_ENABLED=true
LOG_EXPLORER_SERVICE=application
LOG_CHANNEL=observability
Using an existing log stack?

To retain current outputs, keep LOG_CHANNEL=stack and add observability once to that stack. Other channels do not inherit this package's privacy filtering. A disabled observability channel discards records sent to it.

Configure dashboard credentials

Generate a secure password hash through an interactive terminal prompt:

Terminal
php artisan log-explorer:password

Copy the generated hash line into the private application .env. Then add:

.env
LOG_EXPLORER_DASHBOARD_ENABLED=true
LOG_EXPLORER_AUTH_MODE=credentials
LOG_EXPLORER_USERNAME=log-operator
# Add the generated LOG_EXPLORER_PASSWORD_HASH='...' line

There is no default password. The password hash is configuration only; do not paste a plaintext password into this setting.

Apply configuration and open the explorer

Terminal
php artisan config:clear
php artisan route:clear
php artisan log-explorer:doctor

Open https://your-app.example/log-explorer in your running Laravel application. In credentials mode you will be redirected to /log-explorer/login.

Local development on a custom port

Run php artisan log-explorer:serve --port=8765 to serve the entire host application on 127.0.0.1:8765. This is restricted to local/development and is not a standalone production dashboard server.

Configuration

#

The publishable file config/log-explorer.php controls logging, retention, privacy, dashboard access, and diagnostics.

SettingDefaultPurpose
enabledfalseExplicitly enable structured log writes
privacy.payload_levelmetadataAllowed modes: none, metadata, safe
privacy.message_modecategoricalGeneric messages by default; opt-in redacted
storage.retention_days14Delete expired daily files
storage.max_file_bytes64 MiBMaximum size of a daily log file
storage.max_scan_bytes8 MiBBound search work per request
storage.max_scan_ms250 msCooperative search time budget
dashboard.enabledfalseExpose the protected explorer routes
dashboard.auth.modecredentialsIndependent credentials or host authentication
dashboard.max_results50Number of events per search window

Approve additional safe context fields

Only explicitly approved, nonsensitive fields can be included in safe mode.

config/log-explorer.php · PHP
'privacy' => [
    'payload_level' => 'safe',
    'message_mode' => 'categorical',
    'safe_fields' => ['operation', 'count', 'code'],
    // Keep the other published privacy settings unchanged.
],
Avoid logging untrusted text

Approved fields still need a data review. Regex redaction cannot reliably remove every secret or personal detail. Fixed developer-controlled event identifiers are safer than free-form messages.

Logging & exceptions

#

Use Laravel's normal Log facade. Once your application routes records to the structured channel, calls to standard PSR/Monolog log levels work without another API.

Laravel application · PHP
use Illuminate\Support\Facades\Log;

Log::info('Application ready', [
    'event' => 'application.ready',
    'count' => 1,
]);

Log::warning('Checkout retry', [
    'event' => 'checkout.retry',
    'count' => 2,
]);

Preserve exception details

Pass the exception object under the exception context key so that its type, sanitized origin, and bounded stack trace can be retained.

Laravel application · PHP
try {
    // Application operation...
} catch (\Throwable $exception) {
    Log::error('Checkout failed', [
        'event' => 'checkout.failed',
        'exception' => $exception,
    ]);
}

Laravel's existing exception reporter remains authoritative; the package does not install a duplicate reporter. Avoid using both report($exception) and an explicit log call for the same failure unless duplicate events are intended.

What a record looks like

Illustrative sanitized JSONL event · JSON
{
  "schema_version": "1.0",
  "timestamp": "2026-11-17T18:15:00.000Z",
  "level": "WARNING",
  "environment": "production",
  "application": "marketplace",
  "service": "application",
  "event": "checkout.retry",
  "message": "Application log event",
  "context": { "count": 2 }
}

Log explorer

#

The explorer is a lightweight Blade + vanilla JavaScript interface. It supports severity filters, literal search, service and event filters, request IDs, exception classes, route names, HTTP statuses, date ranges, and newest/oldest order.

Laravel Logger log explorer dashboard, with structured event table and filters
Explorer dashboard · Screenshot from the repository (requires internet to load)

Explore event details

  • Overview: event, severity, service, environment and request metadata.
  • Exception: sanitized exception information and bounded trace frames.
  • Context: approved metadata in a readable tree.
  • JSON / Raw: structured output and the stored, sanitized JSONL line.
  • Request grouping: filter events sharing a correlation ID.

Bounded searching

Searches scan a controlled window rather than the entire archive. Use Next window to continue. Cursors are encrypted, tied to the filters, and expire after 15 minutes. Searching is performed through a protected POST request with CSRF verification; terms are not kept in the address bar.

No legacy log import

The explorer reads only this package's structured JSONL source. It does not automatically parse existing laravel.log or other unrelated log channels.

Request correlation

#

Opt into request IDs and route metadata with the package middleware. In a Laravel application using bootstrap/app.php:

bootstrap/app.php · PHP
use Fiachehr\LaravelLogger\Http\CorrelateRequest;

// Inside your existing withMiddleware callback:
$middleware->web(prepend: [CorrelateRequest::class]);
$middleware->api(prepend: [CorrelateRequest::class]);

Register this once per appropriate middleware group after the route is matched. The package captures the HTTP method, route template/name and a generated ID, not raw headers, query strings, IPs or request bodies.

Queue lifecycle hooks add class and attempt metadata while keeping job payloads out of log records. Correlation groups related events; it is not distributed tracing.

Diagnostic helpers

#

Optional helpers make it possible to inspect an approved, bounded summary of a value without printing its entire object graph.

Laravel application · PHP
use function Fiachehr\LaravelLogger\log_dump;

log_dump(['count' => 3], 'checkout.state');

First enable diagnostics.enabled in config/log-explorer.php. The helper continues execution, recording summaries rather than arbitrary object content.

About log_dd()

The namespaced log_dd() is allowed to stop execution only when logging, diagnostics and allow_stop are enabled and the application is running in local or development. Native Laravel/PHP dump() and dd() are not intercepted.

Storage & retention

#

By default, records are stored in private daily files under:

Filesystem path
storage/logs/log-explorer/events-YYYY-MM-DD.jsonl

The writer uses file locks, single-line JSON records, file-size limits, and protective checks for unsafe file targets. Directory and file permissions are restricted to owner access on supported systems.

Retention cleanup

Expired files are pruned during writes, but an idle application may not write every day. Schedule the dedicated prune command when retention must continue during idle periods:

Terminal / scheduled cron
php artisan log-explorer:prune

The command removes only expired files matching the package's daily filename pattern in the configured log root. The package does not register a scheduler automatically.

Operational limits

Default retention is 14 days and the daily file cap is 64 MiB. The writer rejects records when its daily quota is reached. Monitor disk usage and errors; this is file-based observability, not a centralized log pipeline.

Authentication

#

Choose one of two modes. All explorer pages, JSON endpoints and dashboard assets are protected.

Independent credentials (default for new configs)

Use a separately configured username and password hash. The dashboard maintains its own state within Laravel's session infrastructure, rotates session IDs and supports logout revocation. A persistent session store and cache are required.

.env
LOG_EXPLORER_AUTH_MODE=credentials
LOG_EXPLORER_USERNAME=log-operator
# Also set LOG_EXPLORER_PASSWORD_HASH via the password command.

Use your application's authentication

Set LOG_EXPLORER_AUTH_MODE=host and define the configured Gate in your application. This example assumes your User model has an application-owned permission attribute:

App service provider · PHP
use App\Models\User;
use Illuminate\Support\Facades\Gate;

Gate::define('viewLogExplorer',
    fn (User $user): bool => (bool) $user->is_log_operator
);

Replace is_log_operator with your application's real role/permission rule. A missing or denied Gate fails closed. In host mode, users authenticate through your existing application login.

Production access

Use HTTPS, secure session cookies, least-privilege operators and a persistent shared rate-limit cache. The package does not provide multi-user operator management or built-in MFA.

Architecture

#

The implementation uses Laravel's standard logging integration and separates formatting, privacy policy, storage, search, and dashboard authorization.

There are no database migrations, outgoing telemetry calls, remote log collectors or required frontend frameworks.

Security & privacy

#
  • Disabled by default: neither the explorer nor logging is activated just by installation.
  • Controlled context: metadata allowlists and sensitive-key filtering minimize accidental leakage.
  • Safe exception formatting: bounded trace depth and paths without trace arguments.
  • Protected endpoints: credential sessions or host authorization, CSRF and rate limiting.
  • Safer output: escaped Blade templates, DOM text rendering and restrictive response headers.
  • Private files: fixed daily names, path restrictions, symlink/hardlink checks and owner-only permissions.
  • Bounded reads: validated filters, opaque expiring cursors and search budgets.
Privacy boundary

No library can guarantee removal of every secret from arbitrary free-text messages. Keep categorical messages in production, avoid logging request bodies and review each explicitly approved context field. Logs sent to other Laravel channels are not sanitized by this package.

For incident reports, follow the security disclosure policy ↗. Never post production logs or credentials in public issues.

Artisan commands

#
CommandPurpose
log-explorer:installPublish missing configuration with explicit confirmation and show setup guidance
log-explorer:passwordGenerate a password hash through hidden interactive input
log-explorer:doctorCheck setup, credentials/Gate, storage and bundled assets
log-explorer:pruneRemove expired daily files without waiting for another log write
log-explorer:serve --port=8765Launch the host Laravel development server on loopback

Troubleshooting

#
SymptomWhat to check
404 on explorerLogging/dashboard enable flags, custom path, cached routes and config
503 on loginConfigured username, supported password hash, session middleware and persistent cache
419 on POSTSession cookie, CSRF token, HTTPS and same-origin configuration
401 / 403Session expiry, sign-in state, host Gate and guard permissions
429Dashboard rate limit, login attempt budget or shared cache configuration
Empty event tableWrite a structured event, review channel/level settings and run log-explorer:doctor
Generic messagesDefault categorical privacy mode; use fixed event codes and exception objects
Cannot connectStart the host Laravel web server; package installation does not create an HTTP listener

Development & testing

#

The package uses PHPUnit with Orchestra Testbench, Laravel Pint and PHPStan. It does not require Node.js or a frontend build pipeline.

Terminal
composer install
composer test
composer check
composer audit

composer check runs style validation, static analysis and PHP tests. GitHub Actions exercises the supported PHP and Laravel versions.

The package is open source under the MIT license. For contribution guidelines and security reporting, use the repository documents.