How to Log in PHP

Being new to PHP and Laravel Valet, it took quite a bit to find out what’s the best way to console.log while running PHP in Valet. For one, where is the server log if Valet is running in the background? As it turns out, PHP is constantly writing to laravel.log in the storage folder. Here are a couple of techniques that have helped me debug locally with PHP Laravel.

Laravel Valet

Laravel Valet is very convenient when you have several projects running at the same time and needs its own custom domain. With a few simple commands, all the projects are spun up and running with nginx in the background. However, the location of the server logging file was not obvious to me. After searching, I found that the logs are written to the path below.

storage/logs/laravel.log

There are multiple ways to log out to this file, but the easiest one is via the Log library.

\Log::error() or \Log::info()

Another way to log is by using Monolog.

php
use Monolog\Level;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$log = new Logger("name");
$log->pushHandler(new StreamHandler('path/to/your.log', Level::Warning));
$log->warning("some message");

PHP Artisan Serve

Sometimes, I find it easier to run php artisan serve to start my project instead of running valet in the background. From there, a server log is displayed on the terminal and there are lots of logging choices for debugging. A convenient standard for me is error_log, but there’s a catch to getting it to print on the terminal. The standard example for error_log is error_log("a debug message").

However, if you look closely at the method definition for error_log, there are many configurations. For example, you can write the log into different destinations. But to get the log display on the terminal, the error_log type should be 4, where the message is sent directly to the Server API (SAPI) logging handler. You can read more about SAPI here. Here is a sample log for what I would use to debug an object.

error_log(json_encode($myObject, JSON_PRETTY_PRINT), 4)

Techniques for Logging and Local Debugging in PHP

Although there are many ways to do logging in PHP, these are my easiest go-to methods to get started. Now no matter if you’re running in Laravel Valet or PHP Artisan Serve, you can get quick feedback from the code and debug errors easily.