yapro/monolog-ext

非常实用的Monolog扩展

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

This package is not auto-updated.

Last update: 2024-09-20 12:34:37 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,示例

$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 扩展为您提供了处理和记录不同级别错误的机会。

用法

只需像下面那样使用您的logger即可

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