Laravel Cloud is here! Zero-config managed infrastructure for Laravel apps. Deploy now.

Split Log Levels Between Stdout and Stderr With Laravel

Published on by

Split Log Levels Between Stdout and Stderr With Laravel image

Have you ever wanted to log specific levels in Laravel? Sure, you can use the level config option to specify the minimum level to log, but what if you only want Debug and Info logs to go in a specific logger?

Let's say you are writing a CLI and want to split logging between stdout and stderr. Using something like Laravel Zero or Artisan, you might have the following command to demonstrate sending only stderr logs somewhere:

php artisan my-command 2> storage/logs/stderr.log
 
[2024-10-01 02:48:34] development.INFO: Daemon started.
[2024-10-01 02:48:34] development.INFO: The daemon has run 1 times.
[2024-10-01 02:48:37] development.INFO: The daemon has run 2 times.
[2024-10-01 02:48:40] development.INFO: The daemon has run 3 times.
[2024-10-01 02:48:43] development.INFO: The daemon has run 4 times.

And then the stderr logs might look something like the following:

[2024-10-01 02:48:49] development.ERROR: The daemon has run too many times. (6 times now, come on!)
[2024-10-01 02:48:52] development.ERROR: The daemon has run too many times. (7 times now, come on!)
[2024-10-01 02:48:55] development.ERROR: The daemon has run too many times. (8 times now, come on!)
[2024-10-01 02:48:58] development.ERROR: The daemon has run too many times. (9 times now, come on!)
[2024-10-01 02:49:01] development.ERROR: The daemon has run too many times. (10 times now, come on!)
[2024-10-01 02:49:04] development.ERROR: The daemon has run too many times. (11 times now, come on!)
[2024-10-01 02:49:07] development.ERROR: The daemon has run too many times. (12 times now, come on!)
[2024-10-01 02:49:10] development.ERROR: The daemon has run too many times. (13 times now, come on!)
[2024-10-01 02:49:13] development.ERROR: The daemon has run too many times. (14 times now, come on!)

Configuring Laravel to Filter Log Levels

The trick to configuring Laravel's logger to split logs is using Monolog's FilterHandler, which only lets records of a given level through the wrapped handler. A direct example might look as follows:

use Monolog\Handler\FilterHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Level;
 
// Using minimum and maximum level parameters
$handler = new FilterHandler(
handler: new StreamHandler('php://stdout'),
minLevelOrList: Level::Debug,
maxLevel: Level::Info,
);
 
// Using a list
$handler = new FilterHandler(
handler: new StreamHandler('php://stdout'),
minLevelOrList: [Level::Debug, Level::Info]
);

I've used named arguments to help illustrate how we can configure the FilterHandler in Laravel's logging.php configuration file. We can change the stderr and stdout log channels (or create new ones) with the following configuration, using the stack driver:

<?php
 
return [
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => explode(',', env('LOG_STACK', 'stdout,stderr')),
'ignore_exceptions' => false,
],
 
'stdout' => [
'driver' => 'monolog',
'handler' => \Monolog\Handler\FilterHandler::class,
'formatter' => env('LOG_STDOUT_FORMATTER'),
'with' => [
'handler' => fn () => new StreamHandler('php://stdout'),
'minLevelOrList' => [Monolog\Level::Debug, Monolog\Level::Info],
],
'processors' => [PsrLogMessageProcessor::class],
],
 
'stderr' => [
'driver' => 'monolog',
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'stream' => 'php://stderr',
],
'level' => 'notice',
'processors' => [PsrLogMessageProcessor::class],
],
],
];

Notice how the with keys match the FilterLogger constructor named arguments? The stdout logger will log the debug and info logs, while the stderr logger has the level set to notice to capture any CLI errors of notice or above.

I'd also like to point out that Monolog accepts a Closure for the FilterHandler handler so that the wrapped StreamHandler instance is not created until the log channel is used:

'handler' => fn () => new StreamHandler('php://stdout'),

Capturing logs in this manner is helpful in headless/daemon CLI commands when we send logs from a container to a logging service. For example, format error logs with JSON for consumption by a service like DataDog. Here's an example of the environment settings you might have, illustrated in a compose.yaml file:

services:
cli:
build:
context: .
dockerfile: build/Dockerfile
# Do not output any messages to the console.
# Only logs will be sent.
command: ["daemon", "--quiet"]
environment:
LOG_CHANNEL: "stack"
LOG_LEVEL: "info"
LOG_STACK: "stdout,stderr"
LOG_STDOUT_FORMATTER: "\\Monolog\\Formatter\\JsonFormatter"
LOG_STDERR_FORMATTER: "\\Monolog\\Formatter\\JsonFormatter"

Monolog has many Handlers, Formatters, and Processors available that you can configure in Laravel, and all of the common use-cases are already covered in the logging.php configuration file.

You can learn more about logging in Laravel applications in the official documentation.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Bacancy

Outsource a dedicated Laravel developer for $3,200/month. With over a decade of experience in Laravel development, we deliver fast, high-quality, and cost-effective solutions at affordable rates.

Visit Bacancy
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Bagisto Visual: Theme Framework with Visual Editor for Laravel E-commerce image

Bagisto Visual: Theme Framework with Visual Editor for Laravel E-commerce

Read article
Automate Laravel Herd Worktrees with This Claude Code Skill image

Automate Laravel Herd Worktrees with This Claude Code Skill

Read article
Laravel Boost v2.0 Released with Skills Support image

Laravel Boost v2.0 Released with Skills Support

Read article
Laravel Debugbar v4.0.0 is released image

Laravel Debugbar v4.0.0 is released

Read article
Radiance: Generate Deterministic Mesh Gradient Avatars in PHP image

Radiance: Generate Deterministic Mesh Gradient Avatars in PHP

Read article
Speeding Up Laravel News With Cloudflare image

Speeding Up Laravel News With Cloudflare

Read article