All Projects → gmponos → guzzle-log-middleware

gmponos / guzzle-log-middleware

Licence: MIT license
A Guzzle middleware to log request and responses automatically

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to guzzle-log-middleware

guzzlehttp-cloudflare
Guzzle middleware to pass through Cloudflare protection
Stars: ✭ 31 (-49.18%)
Mutual labels:  guzzle, guzzlehttp, guzzle-middleware
guzzle-oauth2-subscriber
OAuth 2.0 Client for Guzzle 4, 5, 6 and 7 with PHP 5.4 - PHP 8.0 - no more dependency hell!
Stars: ✭ 112 (+83.61%)
Mutual labels:  guzzle, guzzlehttp, guzzle-middleware
LogDNA-Android-Client
Android client for LogDNA
Stars: ✭ 22 (-63.93%)
Mutual labels:  log, logger
JJSwiftLog
Swift log library for all platform
Stars: ✭ 51 (-16.39%)
Mutual labels:  log, logger
sprout
Golang logging library supporting log retrieval.
Stars: ✭ 85 (+39.34%)
Mutual labels:  log, logger
datalogger
DataLogger foi projetado para ser uma biblioteca simples de log com suporte a vários providers.
Stars: ✭ 46 (-24.59%)
Mutual labels:  log, logger
log
Aplus Framework Log Library
Stars: ✭ 14 (-77.05%)
Mutual labels:  log, logger
guzzle-jwt-middleware
Guzzle Jwt middleware
Stars: ✭ 24 (-60.66%)
Mutual labels:  guzzlehttp, guzzle-middleware
PhpBotFramework
A framework for Telegram Bot API written in PHP.
Stars: ✭ 56 (-8.2%)
Mutual labels:  composer, guzzle
logger
Gin middleware/handler to logger url path using rs/zerolog
Stars: ✭ 119 (+95.08%)
Mutual labels:  logger, logger-middleware
log
A simple to use log system, minimalist but with features for debugging and differentiation of messages
Stars: ✭ 21 (-65.57%)
Mutual labels:  log, logger
l
Cross-platform html/io [L]ogger with simple API.
Stars: ✭ 26 (-57.38%)
Mutual labels:  log, logger
Project
⭐️ Antares Project Application Skeleton. This is the very first place you should start. It allows you to create a brand new awesome project in easy few steps.
Stars: ✭ 84 (+37.7%)
Mutual labels:  composer, logger
The-PHP-Workshop
A New, Interactive Approach to Learning PHP
Stars: ✭ 30 (-50.82%)
Mutual labels:  composer, guzzle
ng-logger
Angular logger service
Stars: ✭ 65 (+6.56%)
Mutual labels:  log, logger
mastodon-api-php
PHP wrapper for the Mastodon API.
Stars: ✭ 12 (-80.33%)
Mutual labels:  composer, guzzle
apollo-log
A logging extension for the Apollo GraphQL Server
Stars: ✭ 64 (+4.92%)
Mutual labels:  log, logger
Monolog Bundle
Symfony Monolog Bundle
Stars: ✭ 2,532 (+4050.82%)
Mutual labels:  log, logger
Golog
A high-performant Logging Foundation for Go Applications. X3 faster than the rest leveled loggers.
Stars: ✭ 208 (+240.98%)
Mutual labels:  log, logger
clue
a extremely high performance log library for android. 高性能的Android日志库
Stars: ✭ 27 (-55.74%)
Mutual labels:  log, logger

Guzzle Log Middleware

codecov Total Downloads Build Status MIT licensed

This is a middleware for guzzle that will help you automatically log every request and response using a PSR-3 logger.

The middleware is functional with version 6 of Guzzle.

Install

Via Composer

$ composer require gmponos/guzzle_logger

Usage

Simple usage

use GuzzleLogMiddleware\LogMiddleware;
use GuzzleHttp\HandlerStack;

$logger = new Logger();  //A new PSR-3 Logger like Monolog
$stack = HandlerStack::create(); // will create a stack stack with middlewares of guzzle already pushed inside of it.
$stack->push(new LogMiddleware($logger));
$client = new GuzzleHttp\Client([
    'handler' => $stack,
]);

From now on each request and response you execute using $client object will be logged. By default the middleware logs every activity with level DEBUG.

Advanced initialization

The signature of the LogMiddleware class is the following:

\GuzzleLogMiddleware\LogMiddleware(
    \Psr\Log\LoggerInterface $logger, 
    \GuzzleLogMiddleware\Handler\HandlerInterface $handler = null, 
    bool $onFailureOnly = false, 
    bool $logStatistics = false
);
  • logger - The PSR-3 logger to use for logging.
  • handler - A HandlerInterface class that will be responsible for logging your request/response. Check Handlers sections.
  • onFailureOnly - By default the middleware is set to log every request and response. If you wish to log the HTTP messages only when guzzle returns a rejection set this as true or when an exception occurred. Guzzle returns a rejection when http_errors option is set to true.
  • logStatistics - If you set this option as true then the middleware will also log statistics about the HTTP transaction.

Handlers

In order to make the middleware more flexible we allow the developer to initialize it with a handler. A handler is the class that will be responsible for logging the HTTP message and it must implement a HandlerInterface.

As an example let's say that we create the following handler:

<?php
namespace GuzzleLogMiddleware\Handler;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\RequestInterface;
use GuzzleHttp\TransferStats;
use Psr\Log\LoggerInterface;

/** A simple handler that logs only requests */
final class SimpleHandler implements HandlerInterface
{
    public function log(
        LoggerInterface $logger,
        RequestInterface $request,
        ?ResponseInterface $response = null,
        ?\Throwable $exception = null,
        ?TransferStats $stats = null,
        array $options = []
    ): void {
        $logger->debug('Guzzle HTTP request: ' . \GuzzleHttp\Psr7\str($request));
        return;
    }
}

We can pass the handler above during construction of the middleware.

<?php
use GuzzleLogMiddleware\LogMiddleware;
use GuzzleHttp\HandlerStack;

$logger = new Logger();  //A new PSR-3 Logger like Monolog
$stack = HandlerStack::create(); // will create a stack stack with middlewares of guzzle already pushed inside of it.
$stack->push(new LogMiddleware($logger, new SimpleHandler()));
$client = new GuzzleHttp\Client([
    'handler' => $stack,
]);

From now on all Requests will be logged. Note that at the example above only requests are logged.

Important

If no handler is passed the middleware will initialize it's own handler. At the moment the default one is MultiRecordArrayHandler

MultiRecordArrayHandler

This is the default handler used from the middleware. This handler uses internally the FixedStrategy and logs all request and responses with level debug. This handler adds a separate log entry for each Request, Response, Exception or TransferStats. The information about each object are added as a context array to the log entry.

StringHandler

This handler uses internally the FixedStrategy and logs all request and responses with level debug. You can initialize this handler with a custom strategy. This handler adds a separate log entry for each Request, Response, Exception or TransferStats. The handler converts the objects to strings and the information about each object are added to the message of the log entry.

Log Level Strategies

Strategies are used to define the LogLevel that the handler will use to log each object.

FixedStrategy

You can use this strategy to log each HTTP Message with a specific level.

StatusCodeStrategy

You can use this strategy to log each HTTP Response with a specific level depending on the status code of the Response.

$strategy = new StatusCodeStrategy(
    LogLevel::INFO, // Default level used for requests or for responses that status code are not set with a different level.
    LogLevel::CRITICAL // Default level used for exceptions.
);
$strategy->setLevel(404, LogLevel::WARNING);
$multiRecordArrayHandler = new MultiRecordArrayHandler($strategy);

$logger = new Logger();  //A new PSR-3 Logger like Monolog
$stack = HandlerStack::create(); // will create a stack stack with middlewares of guzzle already pushed inside of it.
$stack->push(new LogMiddleware($logger, $multiRecordArrayHandler));
$client = new GuzzleHttp\Client([
    'handler' => $stack,
]);

Using options on each request

You can set on each request options about your log.

$client->get('/', [
    'log' => [
        'on_exception_only' => true,
        'statistics' => true,
    ]
]);
  • on_exception_only Do not log anything unless if the response status code is above the threshold.
  • statistics if the on_exception_only option/variable is true and this is also true the middleware will log statistics about the HTTP call.

Change log

Please see CHANGELOG for more information what has changed recently.

Testing

$ composer test

Credits

License

The MIT License (MIT). Please see License File for more information.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].