robmellett/http-logging

一个轻量级的包,用于记录所有的 Guzzle HTTP 请求和响应。


README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

一个轻量级的包,用于记录所有的 Guzzle HTTP 请求和响应。

安装

您可以通过 composer 安装此包

composer require robmellett/http-logging

您可以使用以下命令发布配置文件

php artisan vendor:publish --tag="http-logging-config"

这是发布配置文件的内容

<?php

// config for RobMellett/HttpLogging
return [
    /*
     *  The Laravel Log Channel to send logs to.
     */
    'channel' => 'http_logs',

    /*
     * Customize how the Secure Json Formatter redacts secrets.
     */
    'secure_json_formatter' => [

        /*
         * Secret Values will be replaced with this value.
         */
        'redacted_value' => '[--REDACTED--]',

        /*
         * By default, we will attempt to look for secrets in the Laravel 'config/services.php'.
         *
         * Any values that contain the following words will be redacted:
         * "key", "secret", "password", "hash", "token"
         */
        'extract_service_secrets' => true,

        /*
         * Specific values to redact from the logs.
         */
        'secrets' => [
            // e.g
            // env('API_SECRET'),
        ],

        /*
         * Regular expressions to redact from the logs.
         */
        'regexes' => [
            // e.g
            // '/Bearer\s\w+/',
        ],
    ],
];

使用方法

您可以通过以下方式将此中间件添加到 Laravel Http 客户端或 Guzzle。

use RobMellett\HttpLogging\HttpLogging;

Http::withMiddleware(new HttpLogging())
    ->asJson()
    ->get('https://jsonplaceholder.typicode.com/posts');

您可以通过在 Laravel 日志配置文件中添加以下内容来配置日志格式化程序。

// config/logging.php

'channels' => [
    // ...Previous config
    
    'http_logs' => [
        'driver' => 'single',
        'path' => storage_path('logs/laravel.log'),
        'level' => 'debug',

        // This will remove sensitive values such as "key", "secret", "hash", "token" from the logs
        'formatter' => RobMellett\HttpLogging\Support\SecureJsonFormatter::class
        
        // Or if you would prefer to send sensitive data to the logs
        //'formatter' => Monolog\Formatter\JsonFormatter::class,
    ],
]

这将把以下 HTTP 请求/响应信息发送到日志中。

一个 HTTP 请求

{
  "message": "Request 0b65fca7-a768-4832-8401-da52aa2885a9",
  "context": {
    "request_id": "0b65fca7-a768-4832-8401-da52aa2885a9",
    "method": "GET",
    "uri": {
      "scheme": "https",
      "host": "jsonplaceholder.typicode.com",
      "path": "/posts",
      "query": "userId=1"
    },
    "headers": {
      "User-Agent": [
        "GuzzleHttp/7"
      ],
      "Host": [
        "jsonplaceholder.typicode.com"
      ],
      "Authorization": [
        "Bearer [--REDACTED--]"
      ],
      "Content-Type": [
        "application/json"
      ]
    }
  },
  "level": 100,
  "level_name": "DEBUG",
  "channel": "testing",
  "datetime": "2023-08-16T10:13:41.356030+00:00",
  "extra": {}
}

一个 HTTP 响应

{
  "message": "Response 0b65fca7-a768-4832-8401-da52aa2885a9",
  "context": {
    "response_id": "0b65fca7-a768-4832-8401-da52aa2885a9",
    "status_code": 200,
    "headers": {
      "Date": ["Wed, 16 Aug 2023 00:41:13 GMT"],
      "Content-Type": ["application/json; charset=utf-8"],
      "Transfer-Encoding": ["chunked"],
      "Connection": ["keep-alive"],
      "X-Powered-By": ["Express"],
      "X-Ratelimit-Limit": ["1000"],
      "X-Ratelimit-Remaining": ["999"],
      "X-Ratelimit-Reset": ["1691921646"],
      "Vary": ["Origin, Accept-Encoding"],
      "Access-Control-Allow-Credentials": ["true"],
      "Cache-Control": ["max-age=43200"],
      "Pragma": ["no-cache"],
      "Expires": ["-1"],
      "X-Content-Type-Options": ["nosniff"],
      "Etag": ["W/\"aa6-j2NSH739l9uq40OywFMn7Y0C/iY\""],
      "Via": ["1.1 vegur"],
      "CF-Cache-Status": ["HIT"],
      "Age": ["18801"],
      "Report-To": [
        "{\"endpoints\":[{\"url\":\"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=gRUkX3pH6GRGwHCE%2BqKF%2ByJRGZs9MkqF8BqXa0nlmYSVzgrcmQkIGfD9lC8IlSXKvSiiyZHxrzgLy8pcOCSMRv5xFh2LyXWOkXDEtFcSr1FINwhjxRwYTZQZIaFzTulP4lUnjlrXdERp57lEXT3C\"}],\"group\":\"cf-nel\",\"max_age\":604800}"
      ],
      "NEL": [
        "{\"success_fraction\":0,\"report_to\":\"cf-nel\",\"max_age\":604800}"
      ],
      "Server": ["cloudflare"],
      "CF-RAY": ["7f75a160dc9991c0-SIN"],
      "alt-svc": ["h3=\":443\"; ma=86400"]
    },
    "body": [
      {
        "userId": 1,
        "id": 1,
        "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
        "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
      }
    ]
  },
  "level": 100,
  "level_name": "DEBUG",
  "channel": "testing",
  "datetime": "2023-08-16T00:41:13.037161+00:00",
  "extra": {}
}

安全 JSON 格式化程序

默认情况下,我们会尝试展平 Laravel config/services.php 数组,并查找包含以下单词的任何键:keysecretpasswordhashtoken,并将它们从日志中排除。

您可以通过将 secure_json_formatter.extract_service_secrets 配置选项设置为 false 来禁用此功能。

<?php

return [
    /*
     * Customize how the Secure Json Formatter redacts secrets.
     */
    'secure_json_formatter' => [
        // ...previous values
    
        'extract_service_secrets' => false,
    ],
];

您可以选择向 secure_json_formatter.secrets 配置选项添加自己的密钥。

<?php

return [
    /*
     * Customize how the Secure Json Formatter redacts secrets.
     */
    'secure_json_formatter' => [
        // ...previous values
    
        /*
         * Specific values to redact from the logs.
         */
        'secrets' => [
            env('SERVICE_API_SECRET'),
        ],
    ],
];

您可以选择向 secure_json_formatter.regexes 配置选项添加自己的正则表达式。

<?php

return [
    /*
     * Customize how the Secure Json Formatter redacts secrets.
     */
    'secure_json_formatter' => [
        // ...previous values
    
        /*
         * Regular expressions to redact from the logs.
         */
        'regexes' => [
            // e.g
            '/Bearer\s\w+/',
        ],
    ],
];

注意:如果您正在使用 Laravel 9x,则需要使用 LegacySecureJsonFormatter 类。

// config/logging.php

'channels' => [
    // ...Previous config
    
    'http_logs' => [
        'driver' => 'single',
        'path' => storage_path('logs/laravel.log'),
        'level' => 'debug',

        // This will remove sensitive values such as "key", "secret", "hash", "token" from the logs
        'formatter' => RobMellett\HttpLogging\Support\LegacySecureJsonFormatter::class
    ],
]

测试

composer test

更新日志

请参阅 更新日志 以获取有关最近更改的更多信息。

贡献

请参阅 贡献指南 以获取详细信息。

安全漏洞

请审查我们关于如何报告安全漏洞的 安全策略

致谢

许可证

MIT 许可证 (MIT)。请参阅 许可证文件 以获取更多信息。