laravel-log-bus maintained by siberfx
Laravel Log Bus
Store every Laravel log record in a database instead of physical log files.
Log Bus is a logging channel for Laravel. Records travel over the bus into MongoDB (the primary store), SQLite, Elasticsearch, OpenSearch, Redis or DynamoDB, with automatic failover between two of them, so storage/logs stays empty and your logs become something you can query.
Log::error('Payment failed', ['order' => 42]); // goes to the database, not to a file
LogBus::query()->minLevel('error')->search('payment')->latest()->limit(20)->get();
- No log files: records go to a database, and if every store is down they go to
stderr, never to disk. - Six engines behind one API: MongoDB, SQLite, Elasticsearch, OpenSearch, Redis and DynamoDB. Switching is one environment variable.
- Automatic failover: when the default store is unreachable, the fallback store takes the records.
- One environment variable to enable: the channel registers itself, nothing to add to
config/logging.php. - Batched writes, with optional queueing, flushed at the end of every request, command and queued job.
- A fluent query API and artisan commands to read, prune and clear logs.
- Self-contained stores: they use their own connections, so logging never fires query events or logs itself.
- Bring your own store with a single
extend()call.
Requirements
| Version | |
|---|---|
| PHP | 8.4 or higher |
| Laravel | 12.x, 13.x |
Each store needs only its own client, and only when you use it:
| Store | Requires |
|---|---|
| MongoDB | ext-mongodb and mongodb/mongodb (^1.21 or ^2.0) |
| SQLite | ext-pdo_sqlite |
| Elasticsearch / OpenSearch | guzzlehttp/guzzle (already part of every Laravel application) |
| Redis | ext-redis or predis/predis |
| DynamoDB | aws/aws-sdk-php |
Installation
composer require siberfx/laravel-log-bus
For the MongoDB store, also install the official client:
composer require mongodb/mongodb
Then run the installer. It publishes config/log-bus.php, prepares the stores (indexes, table) and points LOG_CHANNEL at the bus:
php artisan log-bus:install --set-channel
That is all. The relevant .env values:
LOG_CHANNEL=log-bus
LOG_BUS_STORE=mongodb
LOG_BUS_FALLBACK=sqlite
LOG_BUS_MONGODB_URI=mongodb://127.0.0.1:27017
LOG_BUS_MONGODB_DATABASE=logs
LOG_BUS_MONGODB_COLLECTION=logs
SQLite only
No MongoDB? Use SQLite as the only store. The database file and table are created on first use.
LOG_CHANNEL=log-bus
LOG_BUS_STORE=sqlite
LOG_BUS_FALLBACK=
By default the file is database/log-bus.sqlite; change it with LOG_BUS_SQLITE_DATABASE.
Choosing an engine
Every engine is used the same way: the same log channel, the same query API, the same commands. They differ in what they are good at.
| Engine | Best for | Text search | Old records removed by | Runs on |
|---|---|---|---|---|
| MongoDB | The default: general-purpose log storage | Indexed fields, regex on the message | log-bus:prune |
Your server or Atlas |
| SQLite | Small apps, and the fallback when the main store is down | LIKE scan |
log-bus:prune |
A local file |
| Elasticsearch / OpenSearch | Large volumes that are searched a lot; Kibana / OpenSearch Dashboards | Fast, indexed | log-bus:prune |
A cluster or a managed service |
| Redis | Recent logs, very fast writes, fallback duty | Scan of the time range | log-bus:prune or a maximum entry count |
Memory |
| DynamoDB | AWS serverless applications | Scan of the time range (billed) | Built-in expiry and log-bus:prune |
AWS |
A good rule of thumb:
- Not sure? Keep MongoDB with the SQLite fallback.
- You search logs all day, or already run the Elastic stack: Elasticsearch or OpenSearch.
- You want the fastest possible writes and only care about the last hours or days: Redis.
- You are on AWS and do not want to run a database: DynamoDB.
Any engine can be the default store or the fallback: set LOG_BUS_STORE and LOG_BUS_FALLBACK to mongodb, sqlite, elasticsearch, opensearch, redis or dynamodb. After changing it, run php artisan log-bus:install once to prepare the new store.
MongoDB
Each record is a document in one collection. MongoDB is the primary store because it fits logs naturally: the context is stored as a real nested document, writes are fast, and there is no schema to migrate.
LOG_BUS_STORE=mongodb
LOG_BUS_MONGODB_URI=mongodb://127.0.0.1:27017
LOG_BUS_MONGODB_DATABASE=logs
LOG_BUS_MONGODB_COLLECTION=logs
log-bus:install creates indexes on the time, level and channel. Dates are stored as native dates with millisecond precision. The store connects on first use with a two-second server selection timeout, so an unreachable server fails over quickly instead of hanging the request.
SQLite
Each record is a row in a single table of a dedicated database file, separate from your application's database. There is nothing to run or configure: the file and the table are created on first use, which is what makes it a dependable fallback.
LOG_BUS_STORE=sqlite
LOG_BUS_SQLITE_DATABASE=/absolute/path/to/log-bus.sqlite # default: database/log-bus.sqlite
The database runs in WAL mode so web requests and queue workers can write at the same time. It is meant for one server; if several servers must share logs, use one of the networked engines.
Elasticsearch and OpenSearch
Each record is a document in an index. These engines are built for searching logs, so the query API is at its fastest here, and you can explore the same data in Kibana or OpenSearch Dashboards.
One store serves both engines, because it speaks the REST API they share. No vendor client is required, only Guzzle, which Laravel already ships.
# Elasticsearch
LOG_BUS_STORE=elasticsearch
LOG_BUS_ELASTICSEARCH_URL=https://localhost:9200
LOG_BUS_ELASTICSEARCH_INDEX=logs
LOG_BUS_ELASTICSEARCH_USERNAME=elastic
LOG_BUS_ELASTICSEARCH_PASSWORD=secret
# or, instead of a username and password:
LOG_BUS_ELASTICSEARCH_API_KEY=
# OpenSearch
LOG_BUS_STORE=opensearch
LOG_BUS_OPENSEARCH_URL=https://localhost:9200
LOG_BUS_OPENSEARCH_INDEX=logs
LOG_BUS_OPENSEARCH_USERNAME=admin
LOG_BUS_OPENSEARCH_PASSWORD=secret
How it behaves:
- Index and alias. Records are written through an alias named after the index (
logs) that points at a physical index (logs-000001). If the alias does not exist when the first record arrives, the index is created with the right mapping and the write is retried, so a missinglog-bus:installnever produces a badly mapped index. - Context.
contextandextraare stored in full but not indexed. Log contexts change shape from one record to the next (useris a number here, an object there), which would otherwise make the engine reject records. - Search.
search()matches anywhere in the first 8,000 characters of the message, case-insensitively. Longer messages are stored completely; only the search covers the first 8,000 characters. - Visibility. Like every write to these engines, new records become searchable after the index refresh, about one second by default. Set
'refresh' => 'wait_for'on the store inconfig/log-bus.phpif you need them visible immediately, at the cost of slower writes. - Self-signed certificates. Set
LOG_BUS_ELASTICSEARCH_VERIFY=false(orLOG_BUS_OPENSEARCH_VERIFY=false) in local environments only.
Redis
Records live in memory: a sorted set keeps them in time order and a hash holds their content. Writing a batch is a single round trip, which makes Redis the fastest store to write to and a good fallback for when the main database is down.
It works with the redis PHP extension or with predis/predis, whichever is installed, and uses its own connection rather than Laravel's.
LOG_BUS_STORE=redis
LOG_BUS_REDIS_HOST=127.0.0.1 # default: REDIS_HOST
LOG_BUS_REDIS_PORT=6379 # default: REDIS_PORT
LOG_BUS_REDIS_PASSWORD= # default: REDIS_PASSWORD
LOG_BUS_REDIS_DATABASE=0
LOG_BUS_REDIS_PREFIX=log-bus
LOG_BUS_REDIS_MAX_ENTRIES=100000 # optional: keep only the newest 100,000 records
LOG_BUS_REDIS_CLIENT= # optional: phpredis or predis
How it behaves:
- Memory. Every record takes memory until it is pruned. Set
LOG_BUS_REDIS_MAX_ENTRIESto cap the store: once the limit is reached, the oldest records are dropped as new ones arrive. - Queries. Time ranges are fast. Level, channel and text filters are applied while reading through the time range, so narrow the range with
from()andto()when the store is large. - Persistence. Records survive a restart only if your Redis server persists to disk (RDB or AOF).
- Keys. Everything lives under
{log-bus}:index,{log-bus}:entriesand{log-bus}:sequence. The braces keep the keys together on Redis Cluster. - TLS. Set
LOG_BUS_REDIS_SCHEME=tls.
DynamoDB
Each record is an item in one DynamoDB table. There is no server to run, the table is billed per request, and DynamoDB can expire old records by itself.
composer require aws/aws-sdk-php
LOG_BUS_STORE=dynamodb
LOG_BUS_DYNAMODB_TABLE=logs
LOG_BUS_DYNAMODB_REGION=eu-central-1 # default: AWS_DEFAULT_REGION
LOG_BUS_DYNAMODB_KEY= # default: AWS_ACCESS_KEY_ID
LOG_BUS_DYNAMODB_SECRET= # default: AWS_SECRET_ACCESS_KEY
LOG_BUS_DYNAMODB_TTL_DAYS=30 # optional: let DynamoDB expire records after 30 days
LOG_BUS_DYNAMODB_ENDPOINT= # optional: http://localhost:8000 for DynamoDB Local
Leave the key and secret empty to use the instance role or the default AWS credential chain.
How it behaves:
- Table.
log-bus:installcreates the table (partition keypk, sort keysk, on-demand billing). If the table is missing when the first record arrives, it is created then. - Layout. Records are grouped per day and sorted by time within the day, so writes spread across partitions and reading a time range is cheap. One small
metaitem remembers which days hold records. - Expiry. With
LOG_BUS_DYNAMODB_TTL_DAYSset, every record carries an expiry time and DynamoDB deletes it for free, usually within a couple of days after it expires. Keeplog-bus:prunescheduled as well: it removes records on time and tidies the list of days. - Queries and cost. Time ranges are efficient. Level, channel and text filters are applied by DynamoDB after it has read the records, so you pay read capacity for every record in the time range, not only for the matches. Always combine those filters with
from()andto()on a large table. - Limits. One record can be at most 400 KB. A larger one is rejected and goes to the fallback store.
- Permissions. The IAM policy needs
BatchWriteItem,Query,GetItem,UpdateItemandDeleteItemon the table, plusCreateTable,DescribeTableandUpdateTimeToLiveif the package should create it.
How it works
Log::error() ─► log-bus channel ─► buffer ─► bus ─► default store (e.g. MongoDB)
│ │ fails
│ ▼
│ fallback store (e.g. SQLite)
│ │ fails
│ ▼
└──── last resort (stderr)
- The
log-buschannel collects records in memory. - The buffer is written in one batch when it is full, when a record at or above the flush level (
errorby default) arrives, and at the end of every request, artisan command and queued job. - The bus writes the batch to the default store. If that fails, it writes to the fallback store, and skips the failed store for
retry_afterseconds so a dead server does not slow down every write. - If no store accepts the batch, it is printed to
stderr(or passed to your own callback). Logging never throws and never takes your application down.
Laravel's emergency logger, which normally writes storage/logs/laravel.log when a channel cannot be built, is pointed at stderr as well.
Using the channel
Log exactly as you always do:
use Illuminate\Support\Facades\Log;
Log::info('User {id} logged in', ['id' => $user->id]);
Log::error('Payment failed', ['order' => 42, 'exception' => $e]);
Log::channel('log-bus')->warning('Disk almost full');
Exceptions, objects and dates in the context are reduced to plain data before they are stored.
In a stack
The channel can be combined with others, for example to keep Slack notifications:
// config/logging.php
'stack' => [
'driver' => 'stack',
'channels' => ['log-bus', 'slack'],
],
Customising the channel
The channel is registered for you. To override its options, define it yourself in config/logging.php:
'log-bus' => [
'driver' => 'log-bus',
'level' => 'warning', // minimum level to store
'name' => 'my-app', // stored as the record's channel (default: the environment name)
'buffer_size' => 100,
'flush_level' => 'critical',
],
Reading logs
Query API
use Siberfx\LogBus\Facades\LogBus;
$entries = LogBus::query()
->minLevel('warning') // this level and above
->channel('production')
->search('payment') // case-insensitive, matches the message
->between('2026-01-01', now())
->latest()
->limit(50)
->get(); // Collection of LogEntry
foreach ($entries as $entry) {
$entry->id; // string
$entry->message; // string
$entry->level; // 400
$entry->levelName; // "ERROR"
$entry->channel; // string
$entry->context; // array
$entry->extra; // array
$entry->loggedAt; // DateTimeImmutable, in your app timezone
}
| Method | Description |
|---|---|
level('error', 'critical') |
Only exactly these levels |
minLevel('warning') |
This level and above |
channel('production') |
Only this channel |
search('text') |
Message contains the text (case-insensitive) |
from($date), to($date), between($from, $to) |
Date range, inclusive; strings or DateTimeInterface |
latest(), oldest() |
Sort direction (newest first by default) |
limit(50), offset(100) |
Paging |
get(), first(), count() |
Run the query |
Query another store by name: LogBus::query('sqlite').
Artisan
php artisan log-bus:show # the 20 most recent records
php artisan log-bus:show --min-level=error --limit=50
php artisan log-bus:show --level=error --level=critical --channel=production
php artisan log-bus:show --search="payment" --from="-1 hour"
php artisan log-bus:show --store=sqlite --json
Pruning old logs
Records older than retention_days (30 by default) are removed by the prune command. Schedule it:
// routes/console.php
use Illuminate\Support\Facades\Schedule;
Schedule::command('log-bus:prune')->daily();
php artisan log-bus:prune # use the configured retention
php artisan log-bus:prune --days=7 # override it
php artisan log-bus:clear # delete everything from the default store
Set LOG_BUS_RETENTION_DAYS= (empty) to keep records forever.
Commands
| Command | Description |
|---|---|
log-bus:install |
Publish the config and prepare the stores. --set-channel writes LOG_CHANNEL to .env; --store= limits it to given stores; --no-publish skips the config file. |
log-bus:show |
Show recent records, with filters. |
log-bus:prune |
Delete records older than the retention period. |
log-bus:clear |
Delete every record from a store (asks for confirmation in production). |
Configuration
Publish the file with php artisan vendor:publish --tag=log-bus-config. Every option is documented inside it; the most used ones are available as environment variables:
| Variable | Default | Description |
|---|---|---|
LOG_BUS_STORE |
mongodb |
The default store: mongodb, sqlite, elasticsearch, opensearch, redis or dynamodb |
LOG_BUS_FALLBACK |
sqlite |
Store used when the default one fails; empty to disable |
LOG_BUS_LAST_RESORT |
stderr |
When every store failed: stderr or null (drop) |
LOG_BUS_RETRY_AFTER |
30 |
Seconds a failed store is skipped within the same process |
LOG_BUS_LEVEL |
LOG_LEVEL |
Minimum level stored |
LOG_BUS_BUFFER_SIZE |
50 |
Records per batch; 1 writes every record immediately |
LOG_BUS_FLUSH_LEVEL |
error |
Records at or above this level are written immediately |
LOG_BUS_QUEUE |
false |
Write batches from a queued job |
LOG_BUS_QUEUE_CONNECTION |
default | Queue connection for that job |
LOG_BUS_QUEUE_NAME |
default | Queue name for that job |
LOG_BUS_RETENTION_DAYS |
30 |
Age after which log-bus:prune deletes records |
LOG_BUS_MONGODB_URI |
mongodb://127.0.0.1:27017 |
MongoDB connection string |
LOG_BUS_MONGODB_DATABASE |
logs |
MongoDB database |
LOG_BUS_MONGODB_COLLECTION |
logs |
MongoDB collection |
LOG_BUS_SQLITE_DATABASE |
database/log-bus.sqlite |
SQLite database file |
LOG_BUS_SQLITE_TABLE |
logs |
SQLite table |
The variables of the other engines are listed in Choosing an engine.
Queueing writes
With LOG_BUS_QUEUE=true, batches are handed to the WriteLogEntries job instead of being written during the request. If the queue itself is unavailable, the batch is written directly.
Handling total failure
To be notified when no store accepted a batch, register a callback (for example in a service provider). It replaces the last_resort behaviour:
LogBus::onFailure(function (array $entries, array $errors) {
// $entries: list of LogEntry, $errors: store name => Throwable
});
Stored format
Every store holds the same fields:
| Field | Type | Example |
|---|---|---|
message |
string | Payment failed |
level |
integer | 400 |
level_name |
string | ERROR |
channel |
string | production |
context |
document / JSON | {"order": 42} |
extra |
document / JSON | {} |
logged_at |
date (UTC) | 2026-01-15T12:00:00.000Z |
Times are always stored in UTC and returned in your application's timezone. MongoDB, Elasticsearch and OpenSearch keep millisecond precision; SQLite, Redis and DynamoDB keep microseconds. Redis and DynamoDB store context and extra as JSON text.
Custom stores
Implement Siberfx\LogBus\Contracts\LogStore and register a driver:
use Siberfx\LogBus\Facades\LogBus;
// In a service provider's boot() method
LogBus::extend('clickhouse', fn ($app, array $config) => new ClickHouseStore($config));
// config/log-bus.php
'store' => 'clickhouse',
'stores' => [
'clickhouse' => ['driver' => 'clickhouse', 'host' => 'localhost:8123'],
],
Testing your application
Use the in-memory array store in your tests and assert against it:
config(['log-bus.store' => 'array', 'log-bus.fallback' => null]);
Log::error('Payment failed');
expect(LogBus::query()->search('Payment failed')->count())->toBe(1);
Testing the package
composer test
The suite is written in Pest. The same tests run against every engine; an engine whose server is not reachable is skipped. On CI every engine is required.
| Engine | Variable | Default |
|---|---|---|
| MongoDB | LOG_BUS_MONGODB_URI |
mongodb://127.0.0.1:27017 |
| Redis | LOG_BUS_TEST_REDIS_HOST, LOG_BUS_TEST_REDIS_PORT |
127.0.0.1, 6379 |
| Elasticsearch | LOG_BUS_TEST_ELASTICSEARCH_URL |
http://127.0.0.1:9200 |
| OpenSearch | LOG_BUS_TEST_OPENSEARCH_URL |
http://127.0.0.1:9201 |
| DynamoDB Local | LOG_BUS_TEST_DYNAMODB_ENDPOINT |
http://127.0.0.1:8000 |
Set LOG_BUS_TEST_REQUIRE_STORES=true to fail instead of skip when an engine is unreachable.
Changelog
See CHANGELOG.md.
Credits
License
The MIT License (MIT). See LICENSE.md.