Extending PHP Function Logging with Laravel
This article demonstrates how to install the Monolog package, configure a custom logging channel in Laravel's config/logging.php, and use the Log facade to record custom messages, including a practical middleware example that logs API request details such as method, URI, and execution duration.
Extending PHP Function Logging with Laravel
Laravel provides a concise way to extend PHP function logging, allowing you to easily add support for custom logging in your application.
Installation
Install the monolog/monolog package via Composer:
composer require monolog/monologConfiguration
Add the following configuration to config/logging.php :
'channels' => [
'custom' => [
'driver' => 'monolog',
'handler' => 'custom',
'formatter' => env('LOG_CUSTOM_FORMATTER', 'default'),
'level' => env('LOG_CUSTOM_LEVEL', 'debug'),
],
],
'handlers' => [
'custom' => [
'type' => 'monolog',
'path' => env('LOG_CUSTOM_PATH', storage_path('logs/custom.log')),
],
],Usage
Use the \Illuminate\Support\Facades\Log facade to write custom logs:
Log::channel('custom')->debug('Custom log message');Practical Example
Create a middleware to log API request and response details, including method, URI, and execution duration:
class ApiRequestLogMiddleware
{
public function handle($request, $next)
{
$start = microtime(true);
$response = $next($request);
$duration = microtime(true) - $start;
Log::channel('api')->info('Request: {method} {uri} - Duration: {duration} ms', [
'method' => $request->method(),
'uri' => $request->uri(),
'duration' => round($duration * 1000, 2),
]);
return $response;
}
}PHP8 video tutorial
Scan the QR code to receive free learning materials
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.