yapro/debug

非常实用的 Monolog 扩展

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

This package is not auto-updated.

Last update: 2024-09-28 16:51:54 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 中。这有助于您格式化错误并使用 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