farjadtahir / logward
A secure, high volume log driver for Laravel with optional PII redaction, detail profiles and pluggable destinations.
Fund package maintenance!
Requires
- php: ^8.2
- ext-curl: *
- ext-json: *
- ext-mbstring: *
- ext-openssl: *
- ext-zlib: *
- illuminate/bus: ^12.0 || ^13.0
- illuminate/console: ^12.0 || ^13.0
- illuminate/contracts: ^12.0 || ^13.0
- illuminate/queue: ^12.0 || ^13.0
- illuminate/support: ^12.0 || ^13.0
- monolog/monolog: ^3.0
Requires (Dev)
- larastan/larastan: ^3.0
- laravel/pint: ^1.18
- orchestra/testbench: ^10.0 || ^11.0
- pestphp/pest: ^3.0 || ^4.0
- pestphp/pest-plugin-laravel: ^3.0 || ^4.0
- phpbench/phpbench: ^1.4
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
A secure, high volume log driver for Laravel. Logward redacts personal data before it leaves your app, lets you choose how much detail each channel keeps, and sends logs to the destinations you configure.
Status: Version 1.0.0. Every feature is built and covered by automated tests and stress runs. The Azure Monitor and Datadog destinations follow the documented APIs but have not yet been verified against the live services. If you use either, please share how it went in a live test report.
Features in this release
- PII redaction you can switch on or off per channel, with three modes: mask, keyed hash (so records about one user still correlate) or remove.
- Key based and pattern based detection: sensitive keys such as
passwordoremailat any depth, plus built in patterns for emails, card numbers (Luhn checked), IPv4 addresses, JWTs, bearer tokens and US SSNs. You can add your own patterns. - Detail profiles (
minimal,standard,full, or your own) that control context, extra fields, stack traces and message length without touching call sites. - JSON Lines output ready for log shippers. Newlines inside messages are escaped, so user input cannot forge log lines.
- Local file destination with daily rotation, retention, file permissions and locking.
- Encrypted logs: each line encrypted on its own with AES 256 GCM, with key ids and rotation.
- Tamper evidence: a keyed hash chain that detects edited, deleted, reordered or inserted lines.
- Artisan tools:
logward:key,logward:decryptandlogward:verify. - Azure Monitor Logs through the current Logs Ingestion API, with client secret or managed identity.
- Datadog through the HTTP logs intake, with reserved attributes filled in.
- Any HTTP endpoint, with optional HMAC request signing.
- Resilient delivery: retries with backoff and jitter, Retry-After support, a circuit breaker shared across workers, automatic splitting of oversized batches, and partial failure tracking so nothing is lost or sent twice.
- Three delivery modes: send directly, through a Laravel queue, or spool to disk and ship from a separate worker so requests never wait on the network.
- Volume controls: per level sampling, folding of repeated messages, and a per process rate limit against log floods.
- Operations tools:
logward:ship,logward:replay,logward:test,logward:status, and a section inphp artisan about. - Built for volume: config is compiled once, records below the channel level skip all processing, each record is formatted once, and lines are written in batches through one reused file handle.
- Never breaks your app: failed batches go to a fallback file, internal errors go to a rate limited
error_lognotice, and nothing is thrown at the code that calledLog::info(). - Extensible: add your own destinations and processors.
Requirements
- PHP 8.2 or newer (8.3 or newer for Laravel 13)
- Laravel 12 or 13
Installation
composer require farjadtahir/logward php artisan vendor:publish --tag=logward-config
Add a channel to config/logging.php:
'channels' => [ 'secure' => [ 'driver' => 'logward', 'channel' => 'production', // a key under "channels" in config/logward.php 'level' => env('LOG_LEVEL', 'debug'), ], // Or make it part of your stack: 'stack' => [ 'driver' => 'stack', 'channels' => ['secure'], ], ],
Then log as usual:
Log::channel('secure')->info('User jane@example.com signed in', [ 'user_id' => 42, 'password' => 'hunter2', ]);
which writes:
{"timestamp":"2026-12-04T10:15:30.123+00:00","level":"info","channel":"production","message":"User [REDACTED] signed in","context":{"user_id":42,"password":"[REDACTED]"},"extra":{"app":"Shop","env":"production","host":"web1"}}
Configuration
Everything lives in config/logward.php, and the published file explains each option. docs/configuration.md lists every key with its type, default and environment variable. Logward checks the whole file when a channel starts, and an unknown key (usually a typo) stops the channel with a message that suggests the right one. The main sections are:
| Section | What it controls |
|---|---|
profiles |
How much detail is kept: context, extra, traces, message length |
pii |
Redaction mode, sensitive keys, allow list, patterns, custom patterns |
destinations |
Named places to send logs, each with a driver |
channels |
Ties a profile, PII setting, destinations, batching and fallback together |
Useful environment variables:
| Variable | Default | Purpose |
|---|---|---|
LOGWARD_PII_ENABLED |
true |
Global PII switch |
LOGWARD_PII_MODE |
mask |
mask, hash or remove |
LOGWARD_PII_HASH_KEY |
APP_KEY |
Secret for hash mode |
LOGWARD_PROFILE |
standard |
Profile for the default channel |
LOGWARD_BATCH_SIZE |
100 |
Records per batch |
LOGWARD_FLUSH_INTERVAL |
2 |
Seconds before a waiting batch is flushed on the next record |
Turning PII off for one channel
'channels' => [ 'debugging' => [ 'pii' => false, // ... ], ],
Adding a processor
Any invokable class that takes and returns a Monolog\LogRecord works. Processors run before profile trimming and redaction, so anything they add is still cleaned.
'processors' => [App\Logging\AddRequestId::class],
Adding a destination
Register a driver in a service provider, then reference it in destinations:
use Logward\Destinations\DestinationRegistry; public function boot(DestinationRegistry $destinations): void { $destinations->extend('kafka', fn (string $name, array $config) => new KafkaDestination($name, $config)); }
Your class implements Logward\Contracts\Destination, which has three methods: name(), send(array $lines) and close(). Throw Logward\Exceptions\DestinationException on failure and Logward will move the batch to the fallback file.
Encrypted and tamper evident logs
Both are switched on per destination, so you can encrypt the local file while still sending readable logs elsewhere.
-
Create the keys:
php artisan logward:key --type=encryption php artisan logward:key --type=integrity
-
Put them in
.env(or your secret store):LOGWARD_ENCRYPTION_KEY=base64:... LOGWARD_INTEGRITY_KEY=base64:... LOGWARD_FILE_ENCRYPT=true LOGWARD_FILE_HASH_CHAIN=true
Encryption and integrity use separate keys, and neither falls back to APP_KEY, so rotating APP_KEY never makes old logs unreadable. If a destination asks for encryption and no key is set, the channel refuses to start rather than writing plain text.
Reading encrypted logs
php artisan logward:decrypt storage/logs/logward-2026-12-04.log php artisan logward:decrypt storage/logs/logward-2026-12-04.log --output=/tmp/plain.log
The file is streamed, so size does not matter. --output never overwrites an existing file and creates the new one readable by its owner only.
Checking for tampering
php artisan logward:verify storage/logs/logward-2026-12-0*.log storage/logs/logward-fallback.log
The command exits with a non zero status if anything is wrong, so it can run on a schedule. It reports edited lines, lines missing from the middle of the log, lines out of order, lines signed with an unknown key, and lines with no chain fields (use --allow-unchained if older, unchained lines are expected).
Each PHP worker keeps its own chain (identified by a random stream id), because many workers append to one file at the same time. Verification does not need the encryption key.
Rotating keys
Give the new key a new id and keep the old key as a previous key:
LOGWARD_ENCRYPTION_KEY_ID=k2 LOGWARD_ENCRYPTION_KEY=base64:NEW... LOGWARD_ENCRYPTION_PREVIOUS_KEYS=k1:base64:OLD...
New lines use k2. Lines written with k1 stay readable for as long as k1 is listed. The integrity key rotates the same way with the LOGWARD_INTEGRITY_* variables.
What a line looks like
{"_enc":{"v":1,"kid":"k1","iv":"...","ct":"...","tag":"..."},"_chain":{"kid":"i1","sid":"9f2c41d07a3be815","seq":41,"prev":"...","mac":"..."}}
Encryption and the chain add roughly 300 bytes per line, so a typical 200 byte record becomes about 500 bytes on disk. In a local benchmark the two together cost about 5 microseconds per record.
Sending logs to the cloud
Add the destination to a channel in config/logward.php:
'channels' => [ 'production' => [ 'destinations' => ['local', 'azure'], // or 'datadog', 'http' // ... ], ],
A channel can send to several destinations at once. Each has its own buffer, retries and circuit breaker, so one slow service never holds up the others.
Azure Monitor Logs
Built to Microsoft's documented API and covered by automated tests, but not yet verified against a live Azure workspace. Please report how it goes.
Logward uses the Logs Ingestion API, not the retired HTTP Data Collector API.
-
Create a custom table, for example
LogwardLogs_CL, with the columnsTimeGenerated(datetime),Level(string),Channel(string),Message(string),Context(dynamic) andExtra(dynamic). -
Create a Data Collection Rule whose stream matches Logward's records and maps them to the table:
{ "location": "westeurope", "kind": "Direct", "properties": { "streamDeclarations": { "Custom-LogwardLogs": { "columns": [ { "name": "timestamp", "type": "datetime" }, { "name": "level", "type": "string" }, { "name": "channel", "type": "string" }, { "name": "message", "type": "string" }, { "name": "context", "type": "dynamic" }, { "name": "extra", "type": "dynamic" } ] } }, "destinations": { "logAnalytics": [ { "workspaceResourceId": "/subscriptions/.../workspaces/your-workspace", "name": "workspace" } ] }, "dataFlows": [ { "streams": ["Custom-LogwardLogs"], "destinations": ["workspace"], "transformKql": "source | project TimeGenerated = timestamp, Level = level, Channel = channel, Message = message, Context = context, Extra = extra", "outputStream": "Custom-LogwardLogs_CL" } ] } } -
Give the app's identity the Monitoring Metrics Publisher role on the DCR.
-
Configure Logward with the DCR's logs ingestion endpoint (or a DCE) and its immutable id:
LOGWARD_AZURE_ENDPOINT=https://your-dcr-xxxx.westeurope-1.ingest.monitor.azure.com LOGWARD_AZURE_RULE_ID=dcr-00000000000000000000000000000000 LOGWARD_AZURE_STREAM=Custom-LogwardLogs # Either a service principal... LOGWARD_AZURE_AUTH=client_secret LOGWARD_AZURE_TENANT_ID=... LOGWARD_AZURE_CLIENT_ID=... LOGWARD_AZURE_CLIENT_SECRET=... # ...or a managed identity (App Service, Functions, Container Apps, VMs, AKS) LOGWARD_AZURE_AUTH=managed_identity LOGWARD_AZURE_CLIENT_ID=... # only for a user assigned identity
Tokens are cached in your cache store and shared by all workers, and renewed five minutes before they expire. For Azure Government or Azure operated by 21Vianet, set LOGWARD_AZURE_AUTHORITY_HOST and LOGWARD_AZURE_AUDIENCE for that cloud.
Azure limits each call to 1 MB and each DCR to 12,000 requests and 2 GB per minute. Logward keeps every call under 1 MB and gzips it, and backs off when Azure asks it to.
Datadog
Built to Datadog's documented API and covered by automated tests, but not yet verified against a live Datadog account. Please report how it goes.
LOGWARD_DATADOG_API_KEY=... LOGWARD_DATADOG_SITE=datadoghq.eu # datadoghq.com, us3.datadoghq.com, us5.datadoghq.com, ap1.datadoghq.com... LOGWARD_DATADOG_SERVICE=shop LOGWARD_DATADOG_TAGS=env:production,team:payments
Records arrive with ddsource, service, hostname and ddtags set. Datadog reads Logward's level as the log status and timestamp as the log date by default, so no pipeline setup is needed. Requests stay within Datadog's limits of 5 MB and 1,000 logs, and are gzipped.
Any HTTP endpoint
LOGWARD_HTTP_URL=https://collector.example.com/logs LOGWARD_HTTP_FORMAT=ndjson # or json for a JSON array LOGWARD_HTTP_SIGNING_SECRET=... # optional
With a signing secret, each request carries X-Logward-Timestamp and X-Logward-Signature: sha256=..., an HMAC of "{timestamp}.{body}" over the exact bytes sent. To check it on the receiving side:
$expected = 'sha256='.hash_hmac('sha256', $timestamp.'.'.$rawBody, $secret); $valid = hash_equals($expected, $signature) && abs(time() - (int) $timestamp) < 300;
Delivery, retries and failures
- Failed requests are retried up to 3 times with growing, randomised waits (200 ms base, 2 s cap). Network errors, 408, 425, 429 and 5xx are retried; other 4xx are not, because sending the same request again cannot fix them.
- A
Retry-Afterheader is honoured. If it asks for a longer wait than the cap, Logward stops retrying and pauses that destination for the requested time. - After 5 failed batches in a row a destination is paused for 30 seconds (the circuit breaker). While paused, batches go straight to the fallback file with no network call. One failure after the pause starts it again.
- A 413 splits the batch in half and sends each half.
- When part of a batch was delivered, only the undelivered lines go to the fallback file, so nothing is sent twice.
- All of these are adjustable per destination with
timeout,connect_timeout,retryandcircuit.
Azure tokens and the circuit breaker state live in your default cache store, so every PHP worker shares them. Set LOGWARD_STATE_STORE to use another store, or memory to keep them in each process.
Network safety
- Destination URLs must use HTTPS (plain HTTP is accepted only for localhost), may not contain credentials, and are checked when the channel starts.
- Certificates are always verified, TLS 1.2 is the minimum, and redirects are never followed.
LOGWARD_ALLOWED_HOSTSrestricts where logs may go, for example*.ingest.monitor.azure.com,http-intake.logs.datadoghq.eu. A channel pointing anywhere else refuses to start.- API keys, client secrets, signing secrets and tokens are hidden from
var_dumpandprint_routput.
Delivery modes
Set delivery per channel (or LOGWARD_DELIVERY). Local file destinations are always written directly; the mode decides how batches reach network destinations.
| Mode | How it works | Use it when |
|---|---|---|
direct (default) |
The PHP process sends at the end of the request or job, or when a buffer fills | You want no extra moving parts |
queue |
Each batch becomes a queued job and a queue worker sends it | You already run queue workers |
spool |
Each batch is written to a local spool file; logward:ship sends it |
You want requests to never touch the network |
Spool and ship
LOGWARD_DELIVERY=spool
Then run the shipper, either as a long running worker under Supervisor:
php artisan logward:ship
or from the scheduler:
Schedule::command('logward:ship --max-time=55')->everyMinute()->withoutOverlapping();
- Batches are written atomically (temporary file, then rename), so the shipper never reads half a batch.
- A spool file is deleted only after its lines are delivered. A crash can cause a resend, never a loss.
- After a partial failure only the undelivered lines stay in the spool.
- Lines the service refuses (400, 413, 422, or too large) move to a
failedfolder next to the spool so they never block what comes after. Everything else, including bad credentials, stays in the spool until it goes through, so fixing the config is enough. - Several shippers can run at once; a lock per destination stops them sending the same batch twice.
- When the disk has less than
LOGWARD_SPOOL_MIN_FREE_MB(512 MB by default) free, batches go to the fallback file instead.
In a local test, writing to the spool cost about 0.5 microseconds per record on the request side.
Queue
LOGWARD_DELIVERY=queue LOGWARD_QUEUE_CONNECTION=redis LOGWARD_QUEUE=logs
Each batch is a ShipLogBatch job. The job never throws, so a failing destination cannot start a loop of error logs about failed log jobs. A temporary failure releases the job with the configured backoff (5, 30, 120, 300 seconds by default, 5 tries); a partial failure queues a new job with only the undelivered lines; a refused payload or the last attempt goes to the fallback file. With the sync connection there is no later attempt, so failures go straight to the fallback file.
Queue drivers limit message size. Amazon SQS accepts 256 KB, so with SQS keep LOGWARD_BATCH_BYTES well below that (for example 200000).
Volume controls
'channels' => [ 'production' => [ 'sampling' => ['debug' => 0.1, 'info' => 0.5], // keep 10% of debug and half of info 'dedupe' => true, // fold repeats into "repeated N more time(s)" 'rate_limit' => 1000, // at most 1000 records per second per process ], ],
All three run before any processing, so dropped records cost almost nothing. Levels not listed under sampling are always kept. Folded repeats and records dropped by the rate limit are reported in summary records, so you always know something was left out.
Fallback files and replay
Failed batches go to storage/logs/logward-fallback-{destination}.log, one file per destination. To send them again:
php artisan logward:replay datadog --dry-run # count the lines
php artisan logward:replay datadog
The file is moved aside first, so new failures start a fresh file while the replay runs. Nothing is deleted: the original is kept as *.replayed-<time>, and lines that still fail are written to *.unsent-<time>, which you can replay with --file.
Artisan commands
| Command | What it does |
|---|---|
logward:test [channel] |
Sends one test record straight to every destination and reports each result |
logward:status |
Shows each channel's settings, spool backlog, refused batches and fallback files |
logward:ship |
Sends spooled batches (--once, --max-time, --sleep, --channel) |
logward:replay {destination} |
Resends a fallback file (--channel, --file, --dry-run) |
logward:key |
Creates an encryption or integrity key |
logward:decrypt {path} |
Decrypts an encrypted log file |
logward:verify {paths} |
Checks the hash chain of log files |
php artisan about also lists each Logward channel.
How it works
Log::info()
→ level check (records below the level stop here)
→ context fields → your processors → detail profile → PII redaction
→ JSON Lines formatter (once per record)
→ gate: sampling, deduplication, rate limit (if enabled)
→ per destination: encryption, then hash chain (if enabled)
→ one buffer per destination (flushed by size, bytes, time, or end of request/job)
→ destination, or the fallback file if it fails
Buffers are flushed when a request or Artisan command ends, after each queued job, and after each Octane request, task or tick.
Error handling
| Situation | What happens |
|---|---|
| Invalid config | ConfigurationException when the channel is built; Laravel switches to its emergency logger and records why |
| Destination fails | The batch is appended unchanged to the fallback file and a notice goes to error_log (at most once a minute) |
| Fallback file fails | The batch is dropped and the notice says so |
| A processor throws | That record is dropped and reported; your request carries on |
| Redaction regex fails | The whole string is replaced (fail closed) |
| Encryption fails | That record is dropped and reported; it is never written in plain text |
| A destination with encryption fails | The fallback file receives the encrypted lines, not plain text |
| A network destination is down | Retries, then the fallback file; repeated failures pause the destination |
| Part of a batch fails | Only the undelivered lines go to the fallback file |
Unknown LOGWARD_STATE_STORE |
ConfigurationException when the channel is built |
| Spool disk nearly full | Batches go to the fallback file instead |
| Queue unreachable when dispatching | The batch goes to the fallback file |
| A service refuses a spooled or queued batch | Moved to the spool's failed folder, or the fallback file in queue mode |
Known limits
- Values are scanned only if they are strings, arrays or objects. Numbers are not pattern checked, so put numeric identifiers under a sensitive key if they must be hidden.
- Objects that are not
Stringable,JsonSerializable, enums, dates or exceptions are logged as[object ClassName]when PII is on, so their properties never leak. - Pattern detection reduces risk; it does not guarantee that no personal data reaches your logs. Review what you log.
- The hash chain cannot detect removal of the most recent lines of a stream, or of a whole stream. Ship logs off the host promptly if that matters to you.
- A batch that goes to the fallback file leaves a gap in the main file's chain. Include the fallback file when you verify.
- Each encryption key is safe for about four billion lines. Rotate well before that.
- Lost encryption keys mean unreadable logs. Back them up.
- In
directmode, network sends happen in the PHP process: at the end of each request (after the response is sent under PHP-FPM), after each queued job, and whenever a buffer fills. A buffer that fills mid request adds the send time to that request. Usespoolorqueuedelivery to keep the network out of requests. - Azure Monitor and Datadog accept a request before indexing it. A successful response means accepted, not yet searchable.
- Fallback files are not resent automatically; run
logward:replayonce the destination is healthy. - Sampling, deduplication and the rate limit work per PHP process. Under PHP-FPM each request starts fresh, so they mainly protect against floods within one request or job.
- The spool keeps logs on local disk until shipped. They are redacted (if PII is on) but not encrypted unless the destination has
encrypton; the spool directory is created readable by its owner and group only.
Testing
composer install composer check # Pint, Larastan and Pest composer bench # PHPBench benchmarks
On every pull request, CI benchmarks the base branch and the pull request on the same machine and fails if anything gets more than 25% slower.
Roadmap
- Core (done): pipeline, redaction, profiles, local file destination
- Security (done): encrypted files (AES 256 GCM), key rotation, hash chain tamper evidence
- Cloud destinations (done): Azure Monitor Logs Ingestion API, Datadog, signed HTTP, retries and circuit breaker
- Reliability (done): queue mode, spool and ship, fallback replay, volume controls, Artisan tools
- Version 1.0 (released): stable configuration and API; live verification of Azure Monitor and Datadog continues through user reports
Support
Logward is free and open source. If it saves you time, you can support its development on Ko-fi:
Contributing and security
See CONTRIBUTING.md. Please report vulnerabilities privately as described in SECURITY.md.
License
MIT. See LICENSE.