Skip to content

Logging ​

Giới thiệu (Introduction) ​

Laravel logging dựa trên "channels" (kênh). Mỗi channel đại diện cho một cách ghi log cụ thể. Ví dụ: channel single ghi vào một file, slack gửi log messages đến Slack. Laravel sử dụng thư viện Monolog bên dưới.

Cấu hình (Configuration) ​

File cấu hình tại config/logging.php. Mặc định, Laravel dùng channel stack — kết hợp nhiều channels.

Channel Drivers có sẵn ​

DriverMô tả
customDriver gọi factory tùy chỉnh
dailyDriver Monolog RotatingFileHandler (xoay file hàng ngày)
errorlogDriver Monolog ErrorLogHandler
monologDriver Monolog factory, dùng bất kỳ handler nào
papertrailDriver Monolog SyslogUdpHandler
singleChannel đơn file/path-based (StreamHandler)
slackDriver Monolog SlackWebhookHandler
stackWrapper tạo channels "multi-channel"
syslogDriver Monolog SyslogHandler

Channel Prerequisites ​

Cấu hình Slack Channel ​

Cần URL url trong config/logging.php:

php
'slack' => [
    'driver' => 'slack',
    'url' => env('LOG_SLACK_WEBHOOK_URL'),
    'username' => 'Laravel Log',
    'emoji' => ':boom:',
    'level' => 'critical',
],

Logging Deprecation Warnings ​

PHP, Laravel và thư viện thường thông báo features sẽ bị xóa. Log deprecation warnings:

php
// Trong config/logging.php
'deprecations' => [
    'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
    'trace' => env('LOG_DEPRECATIONS_TRACE', false),
],

Building Log Stacks ​

Channel stack kết hợp nhiều channels:

php
'stack' => [
    'driver' => 'stack',
    'channels' => ['syslog', 'slack'],
    'ignore_exceptions' => false,
],

Log Level ​

Thuộc tính level xác định mức tối thiểu cần log. Monolog levels (tăng dần severity): debug, info, notice, warning, error, critical, alert, emergency.

Viết Log Messages (Writing Log Messages) ​

Dùng Log facade:

php
use Illuminate\Support\Facades\Log;

Log::emergency($message);
Log::alert($message);
Log::critical($message);
Log::error($message);
Log::warning($message);
Log::notice($message);
Log::info($message);
Log::debug($message);

Thông tin ngữ cảnh (Contextual Information) ​

Truyền array context data:

php
use Illuminate\Support\Facades\Log;

Log::info('User {id} đã đăng nhập.', ['id' => $user->id]);

Ghi vào Channel cụ thể ​

php
use Illuminate\Support\Facades\Log;

Log::channel('slack')->info('Có gì đó xảy ra!');

// Stack on-the-fly
Log::stack(['single', 'slack'])->info('Có gì đó xảy ra!');

On-Demand Channels ​

Tạo channel tại runtime:

php
use Illuminate\Support\Facades\Log;

Log::build([
    'driver' => 'single',
    'path' => storage_path('logs/custom.log'),
])->info('Có gì đó xảy ra!');

Tùy chỉnh Monolog (Monolog Channel Customization) ​

Tùy chỉnh cho Channels ​

Dùng tap trong config để tùy chỉnh Monolog instance:

php
'single' => [
    'driver' => 'single',
    'tap' => [App\Logging\CustomizeFormatter::class],
    'path' => storage_path('logs/laravel.log'),
    'level' => 'debug',
],
php
<?php

namespace App\Logging;

use Illuminate\Log\Logger;
use Monolog\Formatter\LineFormatter;

class CustomizeFormatter
{
    public function __invoke(Logger $logger): void
    {
        foreach ($logger->getHandlers() as $handler) {
            $handler->setFormatter(new LineFormatter(
                '[%datetime%] %channel%.%level_name%: %message% %context%'
            ));
        }
    }
}

Tạo Handler Channels ​

php
'logentries' => [
    'driver' => 'monolog',
    'handler' => Monolog\Handler\SyslogUdpHandler::class,
    'with' => [
        'host' => 'my.logentries.internal.datahubhost.company.com',
        'port' => '10000',
    ],
],

Tạo Custom Channels qua Factories ​

php
'custom' => [
    'driver' => 'custom',
    'via' => App\Logging\CreateCustomLogger::class,
],
php
<?php

namespace App\Logging;

use Monolog\Logger;

class CreateCustomLogger
{
    public function __invoke(array $config): Logger
    {
        return new Logger(/* ... */);
    }
}

Theo dõi Log với Pail ​

Laravel Pail — package xem log trực tiếp từ terminal.

Cài đặt ​

bash
composer require laravel/pail

Sử dụng ​

bash
php artisan pail

Lọc Logs ​

bash
php artisan pail --filter="QueryException"
php artisan pail --message="User"
php artisan pail --level=error
php artisan pail --user=1