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.

php Courses
php Courses
php Courses
Extending PHP Function Logging with Laravel

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/monolog

Configuration

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

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

middlewareloggingPHPMonolog
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.