bizkit/loggable-command-bundle

创建为每个命令或消息处理器指定 Monolog 日志文件的 Symfony 扩展包。

安装: 117

依赖者: 0

建议者: 0

安全: 0

星标: 4

关注者: 2

分支: 0

开放问题: 0

类型:symfony-bundle

v1.5.0 2024-04-06 15:02 UTC

This package is auto-updated.

Last update: 2024-09-06 16:07:38 UTC


README

Build Status Latest Stable Version License Code Coverage

创建为每个命令或消息处理器指定 Monolog 日志文件的 Symfony 扩展包。

功能

  • 动态为每个命令或消息处理器创建专用的 Monolog 文件处理器
  • 使用 Monolog 的控制台处理器在终端内显示输出
  • 支持使用 Monolog 的流或轮转文件处理器,并创建自定义处理器工厂
  • 自动将配置的 Monolog 通道从所有其他具有专用通道的处理程序中排除
  • 允许通过使用 PHP 8 属性或 Doctrine 注解按命令进行配置
  • 支持配置特定日志级别应使用哪个输出流(stdoutstderr

要求

安装

  1. 使用 Composer 需要该扩展包

    composer require bizkit/loggable-command-bundle
  2. config/packages/bizkit_loggable_command.yaml 下创建扩展包配置文件。以下是一个参考配置文件

    bizkit_loggable_command:
    
        # The name of the channel used by the console & file handlers.
        channel_name:         loggable_output
    
        # Configuration options for the console handler.
        console_handler_options:
    
            # The minimum level at which the output is sent to stderr instead of stdout.
            stderr_threshold:     ERROR
            bubble:               true
            verbosity_levels:
                VERBOSITY_QUIET:      ERROR
                VERBOSITY_NORMAL:     WARNING
                VERBOSITY_VERBOSE:    NOTICE
                VERBOSITY_VERY_VERBOSE: INFO
                VERBOSITY_DEBUG:      DEBUG
            console_formatter_options:
                format:               "[%%datetime%%] %%start_tag%%%%level_name%%%%end_tag%% %%message%%\n"
            formatter:            null
    
        # Configuration options for the file handler.
        file_handler_options:
    
            # The path where the log files are stored.
            # A {filename} & {date} placeholders are available which get resolved to the name of the log & current date.
            # The date format can be configured using the "date_format" option.
            path:                 '%kernel.logs_dir%/console/{filename}.log' # Example: '%kernel.logs_dir%/console/{filename}/{date}.log'
    
            # The name of the file handler factory to use.
            type:                 stream
            level:                DEBUG
            bubble:               true
            include_stacktraces:  false
            formatter:            null
            file_permission:      null
            use_locking:          false
            max_files:            0
            filename_format:      '{filename}-{date}'
            date_format:          Y-m-d
    
            # Extra options that can be used in custom handler factories.
            extra_options:        []
    
                # Examples:
                # my_option1:          'some value'
                # my_option2:          true
    
            # Enables configuring services with the use of an annotation, requires the Doctrine Annotation library.
            enable_annotations:   false
    
        # Configuration option used by both handlers.
        process_psr_3_messages:
    
            # Examples:
            # - false
            # - { enabled: false }
            # - { date_format: Y-m-d, remove_used_context_fields: true }
            enabled:              true
            date_format:          ~
            remove_used_context_fields: ~
  3. 通过将其添加到数组中,在 config/bundles.php 中启用扩展包

    Bizkit\LoggableCommandBundle\BizkitLoggableCommandBundle::class => ['all' => true],

用法

该扩展包提供了一种通过为每个服务动态创建一个 Monolog 文件处理器和记录器,将 Symfony 命令Symfony 消息传递的消息处理器的输出记录到专用文件的方法。支持文件处理器包括 streamrotating_file 处理器。要使用其他文件处理器,必须实现并注册一个 自定义处理器工厂

输出记录器还使用控制台处理器在终端内显示输出。可以使用 stderr_threshold 选项设置输出开始发送到 stderr 流而不是 stdout 的日志级别。

还可以将其他 Monolog 处理器添加到输出记录器,如 专用部分 中所述。

命令

在 Symfony 命令中启用输出记录的最简单方法是通过扩展 LoggableCommand 类。可以通过 $outputLogger 属性访问输出记录器。默认情况下,日志文件的名称将是命令名称的蛇形版本,例如 app_my_loggable

namespace App;

use Bizkit\LoggableCommandBundle\Command\LoggableCommand;

class MyLoggableCommand extends LoggableCommand
{
    protected static $defaultName = 'app:my-loggable';

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $this->outputLogger->debug('Debug');
        $this->outputLogger->notice('Notice');

        // ...
    }
}

除了扩展 LoggableCommand 类之外,您还可以使用具有 LoggableOutputInterfaceLoggableOutputTrait。这对于您有一个自定义基本命令类时非常有用。

namespace App;

use Bizkit\LoggableCommandBundle\LoggableOutput\LoggableOutputInterface;
use Bizkit\LoggableCommandBundle\LoggableOutput\LoggableOutputTrait;

class MyLoggableCommand extends MyBaseCommand implements LoggableOutputInterface
{
    use LoggableOutputTrait;

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        // ...
    }
}

消息处理器

还可以通过实现 LoggableOutputInterface 使用输出记录与 Symfony 消息传递的消息处理器。日志文件的名称将是类名的蛇形版本,例如 my_message_handler。可以通过实现 NamedLoggableOutputInterface 来提供自定义名称。

namespace App;

use Bizkit\LoggableCommandBundle\LoggableOutput\LoggableOutputTrait;
use Bizkit\LoggableCommandBundle\LoggableOutput\NamedLoggableOutputInterface;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

class MyMessageHandler implements MessageHandlerInterface, NamedLoggableOutputInterface
{
    use LoggableOutputTrait;

    public function __invoke(MyMessage $myMessage): void
    {
        $this->outputLogger->error('Error');
        $this->outputLogger->info('Info');
    }

    public function getOutputLogName(): string
    {
        return 'my_log_name';
    }
}

PHP 8 属性

默认配置可以通过使用 LoggableOutput PHP 属性 对每个单独的命令或消息处理器进行覆盖。除此之外,它还允许你更改输出记录器使用的 Monolog 文件处理器。

namespace App;

use Bizkit\LoggableCommandBundle\Command\LoggableCommand;
use Bizkit\LoggableCommandBundle\ConfigurationProvider\Attribute\LoggableOutput;

#[LoggableOutput(filename: 'my_custom_name', type: 'rotating_file')]
class MyLoggableCommand extends LoggableCommand
{
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        // ...
    }
}

PHP 属性也可以用作提供自定义日志文件名的替代方法,在这种情况下,不需要实现 NamedLoggableOutputInterface

namespace App;

use Bizkit\LoggableCommandBundle\ConfigurationProvider\Attribute\LoggableOutput;
use Bizkit\LoggableCommandBundle\LoggableOutput\LoggableOutputInterface;
use Bizkit\LoggableCommandBundle\LoggableOutput\LoggableOutputTrait;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

#[LoggableOutput(filename: 'my_log_name')]
class MyMessageHandler implements MessageHandlerInterface, LoggableOutputInterface
{
    use LoggableOutputTrait;

    public function __invoke(MyMessage $myMessage): void
    {
        // ...
    }
}

属性选项从所有声明了 PHP 属性的父类继承。如果父类和子类都定义了相同的选项,子类的选项具有优先级。

namespace App;

use Bizkit\LoggableCommandBundle\ConfigurationProvider\Attribute\LoggableOutput;
use Bizkit\LoggableCommandBundle\LoggableOutput\LoggableOutputInterface;
use Bizkit\LoggableCommandBundle\LoggableOutput\LoggableOutputTrait;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

#[LoggableOutput(path: '%kernel.logs_dir%/messenger/{filename}.log')]
abstract class MyBaseMessageHandler implements MessageHandlerInterface, LoggableOutputInterface
{
    use LoggableOutputTrait;
}

#[LoggableOutput(filename: 'my_log_name')]
class MyMessageHandler extends MyBaseMessageHandler
{
    public function __invoke(MyMessage $myMessage): void
    {
        // ...
    }
}

Doctrine 注释

如果你使用的是 8 版本之前的 PHP,可以使用 Doctrine 注释 来替代 PHP 属性以覆盖默认配置。

  1. 使用 Composer 需求 Doctrine 注释库

    composer require doctrine/annotations
  2. 在配置中启用注释支持

    bizkit_loggable_command:
        file_handler_options:
            enable_annotations: true

LoggableOutput PHP 属性也用作 Doctrine 注释类。

namespace App;

use Bizkit\LoggableCommandBundle\Command\LoggableCommand;
use Bizkit\LoggableCommandBundle\ConfigurationProvider\Attribute\LoggableOutput;

/**
 * @LoggableOutput(filename="my_custom_name", type="rotating_file")
 */
class MyLoggableCommand extends LoggableCommand
{
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        // ...
    }
}

注释选项也继承自所有父类。

将其他 Monolog 处理器添加到输出记录器

要向输出记录器添加其他 Monolog 处理器,对于包含的通道列表,将使用 channel_name 选项定义的 Monolog 通道添加到它们的 channels 列表中。

monolog:
    handlers:
        sentry:
            type: sentry
            dsn: '%sentry_dsn%'
            channels: [ "loggable_output" ]

对于排他的通道列表,禁用自动排除 功能。

注意:在多个输出记录器的情况下,每个输出记录器将使用相同的处理程序实例。

Monolog 通道自动排除

该组件使用的 Monolog 通道会自动从所有具有排他通道列表的其他 Monolog 处理程序中排除。无需手动将通道添加到列表中。

monolog:
    handlers:
        main:
            # ...
            channels: [ "!event" ] # the bundle's channel is excluded automatically, no need to add it manually

禁用自动排除

如果你不希望通道被自动排除在某个处理程序之外,请将带有前缀 !! 的通道添加到 channels 列表中。

monolog:
    handlers:
        main:
            # ...
            channels: [ "!event", "!!loggable_output" ] # this will prevent the channel from being auto-excluded

处理程序工厂

处理程序工厂用于实例化和配置输出记录器使用的文件处理程序。

自定义处理程序工厂

要实现自定义处理程序工厂,只需创建一个实现 HandlerFactoryInterface 接口的服务即可。

namespace App;

use Bizkit\LoggableCommandBundle\HandlerFactory\HandlerFactoryInterface;

class CustomHandlerFactory implements HandlerFactoryInterface
{
    public function __invoke(array $handlerOptions): HandlerInterface
    {
        // configure & return a monolog handler
    }
}

在配置中使用服务的 FQCN

bizkit_loggable_command:
    file_handler_options:
        type: App\CustomHandlerFactory

如果你没有使用 Symfony 的 autoconfigure 功能或希望在使用配置时使用别名,请使用 bizkit_loggable_command.handler_factory 标签标记该服务。

App\CustomHandlerFactory:
    # Prevents the handler factory from being tagged twice,
    # once by the autoconfigure feature & once manually
    autoconfigure: false
    tags:
        - { name: bizkit_loggable_command.handler_factory, type: custom }

bizkit_loggable_command:
    file_handler_options:
        type: custom

为了简化处理程序工厂的配置,该组件提供了一个 AbstractHandlerFactory 类,它可以用于配置一些常见的处理程序功能,例如 PSR 3 日志消息处理器或日志格式化器。

namespace App;

use Bizkit\LoggableCommandBundle\HandlerFactory\AbstractHandlerFactory;
use Monolog\Handler\HandlerInterface;

class CustomHandlerFactory extends AbstractHandlerFactory
{
    protected function getHandler(array $handlerOptions): HandlerInterface
    {
        // return a monolog handler
    }
}

版本管理

该项目遵循 语义版本控制 2.0.0

报告问题

使用 问题跟踪器 报告你可能遇到的问题。

许可

有关许可权利和限制(MIT),请参阅 LICENSE 文件。