devnav2902/utilitylog

在日志中写入自定义消息

1.0.1 2024-05-01 11:02 UTC

This package is auto-updated.

Last update: 2024-10-01 00:09:29 UTC


README

此包可以帮助您写入自定义日志消息,基于 LineFormatter - Monolog

安装

使用以下命令安装最新版本

composer require devnav2902/utilitylog

基本用法

UtilityLog::writeLog('error', 'Foo');
UtilityLog::writeLog('info', 'Bar');

// in try-catch block
try {
     throw new \Exception('Something happened!');
} catch (\Throwable $th) {
     UtilityLog::writeLog('error', 'Error in try-catch block', $th);
}

// contextual information
UtilityLog::writeLog('info', 'User {id} failed to login.', null, ['id' => $user->id]);

文档

使用说明

此包使用 LineFormatter (Monolog),因此您可以设置自定义格式,例如

"[%channel%][%level_name%] %datetime%\n%message% %extra%\n\n"

您可以在配置文件中修改,以下为默认配置

<?php

return [
    'customize_formatter' => "[%channel%][%level_name%] %datetime%\n%message% %extra%\n\n",
    'date_format' => 'Y-m-d H:i:s',
    'message_json_option' => JSON_PRETTY_PRINT,
    'allow_inline_linebreaks' => true,
    'ignore_empty_context_and_extra' => true,
    'include_stacktraces' => false
];

此配置用于 LineFormatter 的参数

class CustomizeFormatter
{
    /**
     * Customize the given logger instance.
     */
    public function __invoke(Logger $logger): void
    {
        foreach ($logger->getHandlers() as $handler) {
            $lineFormatter = new LineFormatter(
                config('utilitylog.customize_formatter'),
                config('utilitylog.date_format'),
                config('utilitylog.allow_inline_linebreaks'),
                config('utilitylog.ignore_empty_context_and_extra'),
                config('utilitylog.include_stacktraces')
            );
            
            $handler->setFormatter($lineFormatter);
        }
    }
}

✍️ 如果要更改默认配置,可以使用以下命令

php artisan vendor:publish --tag=utilitylog-config

这将从包中复制文件到您的 Laravel 项目文件夹 config\utilitylog.php

✍️ 您可以通过访问 URL /view-log/view-log?date=Y-m-d 来查看日志文件,其中 Y-m-d 是日期格式,例如:2024-05-01,这将打开文件:laravel-2024-05-01.log

您可以通过发布视图来自定义视图,使用以下命令

php artisan vendor:publish --tag=utilitylog-views

关于

要求

此包与 PHP 8.1 或更高版本兼容。

许可

Utilitylog 在 MIT 许可证下发布 - 有关详细信息,请参阅 LICENSE 文件。