yapro/monologext

Monolog 的高度有用扩展

v1.0.11 2024-05-17 10:44 UTC

This package is not auto-updated.

Last update: 2024-09-23 12:27:12 UTC


README

真正有用的 Monolog 扩展。

lib tests

安装

在您的 composer.json 文件中添加依赖项或运行

composer require yapro/monolog-ext dev-master

Symfony >= 2.x 的配置

您可以以最简单的方式处理日志,因为这是最简单的方法

monolog:
    channels:
        - deprecation # Deprecations are logged in the dedicated "deprecation" channel when it exists
    handlers:
        main:
            type: service
            id: YaPro\MonologExt\Handler\JsonToStdErrHandler

并且不要忘记将处理程序注册为服务

services:
  YaPro\MonologExt\Handler\JsonToStdErrHandler: ~

您将获得以下功能

  • 将日志写入 stderr ( https://12factor.net/logs )
  • JSON 表示形式
  • 当客户端发送无效的 HTTP 请求(4xx)时忽略日志
  • 应用代码中所有级别的日志记录(src 目录,不在 vendor 目录中)
  • 库(vendor 目录)中 NOTICE 级别及以上的日志记录
  • 智能记录减少(当记录大小超过 8192 字节时从记录上下文中删除键)

以及其他功能,如开发模式。

您还可以配置 JsonToStdErrHandler

您还可以使用 Monolog 处理器集合,这为您提供了处理和记录不同错误的机会。

将所需的应用程序配置添加到您的 config.yml 文件中

services:
  # Adds exception`s information to a log record
  YaPro\MonologExt\Processor\AddInformationAboutExceptionProcessor:
    class: YaPro\MonologExt\Processor\AddInformationAboutExceptionProcessor
    tags:
      - { name: monolog.processor, handler: main }

  # Adds a call stack of the log-record location
  YaPro\MonologExt\Processor\AddStackTraceOfCallPlaceProcessor:
    class: YaPro\MonologExt\Processor\AddStackTraceOfCallPlaceProcessor
    tags:
      - { name: monolog.processor, handler: main }

  # Stop execution when problems occur (very useful in tests)
  YaPro\MonologExt\Processor\StopExecutionWhenProblemProcessor:
    class: YaPro\MonologExt\Processor\StopExecutionWhenProblemProcessor
    tags:
      - { name: monolog.processor, handler: main }

  # Moves the contents of the content field to the field specified in the processor constructor + removes the context field
  YaPro\MonologExt\Processor\RenameContextProcessor:
    class: YaPro\MonologExt\Processor\RenameContextProcessor
    tags:
      - { name: monolog.processor, handler: main, priority: -1 }

  # Moves the contents of the content field to the location specified in the record field + removes the context field
  YaPro\MonologExt\Processor\MoveContextProcessor:
    class: YaPro\MonologExt\Processor\MoveContextProcessor
    tags:
      - { name: monolog.processor, handler: main, priority: -1 }

  # Adds a request as curl command to a log record
  # Old version - https://github.com/yapro/monolog-ext/blob/php5/src/Monolog/Processor/RequestAsCurl.php
  monolog.processor.request_as_curl:
    class: Debug\Monolog\Processor\RequestAsCurl
    arguments: [ "@request_stack" ]
    tags:
      - { name: monolog.processor, handler: main }

  # not implemented yet. Old version - https://github.com/yapro/monolog-ext/blob/php5/src/Monolog/Processor/Guzzle.php
  monolog.processor.guzzle:
    class: Debug\Monolog\Processor\Guzzle
    tags:
      - { name: monolog.processor, handler: main }
  # странная особенность - если не объявить, то возникает ошибка: Cannot autowire service, no such service exists. You
  # should maybe alias this class to one of these existing services: "monolog.formatter.json", "monolog.formatter.loggly".
  # создал вопрос: https://github.com/symfony/symfony/issues/36527
  Monolog\Formatter\JsonFormatter:
    class: Monolog\Formatter\JsonFormatter

然后使用记录器,示例

$logger->info('I just got the logger');
$logger->error('An error occurred');

查看,变量 $e 将被转换为字符串(Monolog 的功能),您将得到:异常消息 + 调试信息

$logger->warning('My warning', array(
   'my' => 'data',
   'exception' => $e,// now you can see the above written custom stack trace as a string
));
$logger->warning('My second warning', array($e));// the short variant of version which you can see the above

默认情况下,\YaPro\MonologExt\VarHelper 通过标准深度级别(等于两个)将额外的数据提取为字符串。但,您可以使用任何深度级别,例如等于五个

$logger->error('An error occurred', [ 'my mixed type var' => (new VarHelper)->dump($myVar, 5) ] );

什么是 ExtraException

ExtraException 是您可以将额外数据添加到其中并抛出的异常。抛出 Monolog ExceptionProcessor 会捕获此异常并将额外数据保存到日志中。示例

throw (new ExtraException())->setExtra('mixed data');

建议

将服务 json_formatter 添加到文件 app/config/config.yml 中。这将帮助您格式化 JSON 中的错误,然后您可以使用 https://elastic.ac.cn/products/kibana 对所有错误进行聚合。

services:
    json_formatter:
        class: Monolog\Formatter\JsonFormatter

并且不要忘记添加 monolog 格式化程序

monolog:
    handlers:
        main:
            formatter: json_formatter

如果您希望收集 HTTP 请求的一些数据,您可以添加 WebProcessor

services:
    monolog.processor.web:
        class: Monolog\Processor\WebProcessor
        tags:
            - { name: monolog.processor, handler: main }

没有 Symfony 框架的项目配置

Monolog Cascade 扩展为您提供处理和记录不同级别错误的机会。

用法

只需像下面这样使用您的记录器即可

Cascade::fileConfig($config);
Log::info('Well, that works!');
Log::error('Maybe not...', ['some'=>'extra data']);

配置您的记录器

Monolog Cascade 支持以下配置格式

  • Yaml
  • JSON
  • PHP 数组

配置结构

以下是一个 PHP 数组配置文件的示例

<?php

$config = [
    'formatters' => [
        'dashed' => [
            //'class' => 'Monolog\Formatter\LineFormatter',
            'class' => \Monolog\Formatter\JsonFormatter::class
            //'format' => '%datetime%-%channel%.%level_name% - %message%'
        ]
    ],
    'handlers' => [
        'console' => [
            'class' => 'Monolog\Handler\StreamHandler',
            'level' => 'DEBUG',
            'formatter' => 'dashed',
            'stream' => 'php://stdout'
        ],
        'info_file_handler' => [
            'class' => 'Monolog\Handler\StreamHandler',
            'level' => 'INFO',
            'formatter' => 'dashed',
            'stream' => './example_info.log'
        ]
    ],
    'processors' => [
        'web_processor' => [
            'class' => 'Monolog\Processor\WebProcessor'
        ]
    ],
    'loggers' => [
        'mainLogger' => [
            'handlers' => [
                0 => 'console',
                1 => 'info_file_handler'
            ],
            'processors' => [
                0 => 'web_processor'
            ]
        ]
    ],
    'disable_existing_loggers' => true,
    'errorReporting' => E_ALL & ~E_DEPRECATED & ~E_STRICT,
];

有关配置的更多详细信息 - https://github.com/theorchard/monolog-cascade

测试

docker build -t yapro/monolog-ext:latest -f ./Dockerfile ./
docker run --rm -v $(pwd):/app yapro/monolog-ext:latest bash -c "cd /app \
  && composer install --optimize-autoloader --no-scripts --no-interaction \
  && /app/vendor/bin/phpunit /app/tests"

开发

docker build -t yapro/monolog-ext:latest -f ./Dockerfile ./
docker run -it --rm --user=$(id -u):$(id -g) --add-host=host.docker.internal:host-gateway -v $(pwd):/app -w /app yapro/monolog-ext:latest bash
composer install -o

使用 xdebug 运行测试

PHP_IDE_CONFIG="serverName=common" \
XDEBUG_SESSION=common \
XDEBUG_MODE=debug \
XDEBUG_CONFIG="max_nesting_level=200 client_port=9003 client_host=host.docker.internal" \
/app/vendor/bin/phpunit /app/tests