PHPackages                             oras/monolog-middleware - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. oras/monolog-middleware

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

oras/monolog-middleware
=======================

PSR-7 Monolog Middleware

v3.0.0(8y ago)2012.1k↓50%7[1 PRs](https://github.com/orasik/monolog-middleware/pulls)MITPHPPHP ^7.1 || ^7.2

Since Jun 3Pushed 4y ago4 watchersCompare

[ Source](https://github.com/orasik/monolog-middleware)[ Packagist](https://packagist.org/packages/oras/monolog-middleware)[ RSS](/packages/oras-monolog-middleware/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (10)Versions (10)Used By (0)

[![Build Status](https://camo.githubusercontent.com/997448b923df2b2ad22fbfa4f708c01a8e7a2b76bce2619ef08883492d4ca079/68747470733a2f2f7472617669732d63692e6f72672f6f726173696b2f6d6f6e6f6c6f672d6d6964646c65776172652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/orasik/monolog-middleware)[![Latest Stable Version](https://camo.githubusercontent.com/445239cf44417cd51e253bd21f09f7dc8024a99708968b9147c7501df90ae0d2/68747470733a2f2f706f7365722e707567782e6f72672f6f7261732f6d6f6e6f6c6f672d6d6964646c65776172652f762f737461626c65)](https://packagist.org/packages/oras/monolog-middleware)[![Total Downloads](https://camo.githubusercontent.com/b60dfafe5605a9c052d8976180bb0d08ac98a8387ec357e8164a0084d8edaf08/68747470733a2f2f706f7365722e707567782e6f72672f6f7261732f6d6f6e6f6c6f672d6d6964646c65776172652f646f776e6c6f616473)](https://packagist.org/packages/oras/monolog-middleware)[![License](https://camo.githubusercontent.com/1a1423c3d98d184921ccce0fad07c771fc74f0c5360bbe889ff19e251814cb2a/68747470733a2f2f706f7365722e707567782e6f72672f6f7261732f6d6f6e6f6c6f672d6d6964646c65776172652f6c6963656e7365)](https://packagist.org/packages/oras/monolog-middleware)

Monolog Logger Middleware
=========================

[](#monolog-logger-middleware)

Monolog Middleware to be used with PSR-7 middleware frameworks like Zend Expressive and Slim.

**Now it does support Zend Expressive `3.*`**

To use with Zend Expressive `1.*` please install version `1.1.4`To use with Zend Expressive `2.*` please install version `2.0.0`

`loggables` setting inspired by Guzzle Log Format. You can set any data in request/response/headers that you want to log from config file rather than in code to give more flexibility in logging more/less data based on your needs.

### Installation

[](#installation)

##### 1) Install middleware using composer

[](#1-install-middleware-using-composer)

```
composer require oras/monolog-middleware
```

##### 2) Add configuration

[](#2-add-configuration)

Then in your Zend Expressive `config/autoload/` directory, created a new config file call it: `logger.local.php`

As a starting point, you can have the following in the file:

```
use Monolog\Logger;

return [
    'monolog' =>
        [
            'logger_name' => 'MyLog',
            'loggables' => '[{host}] {request}/{response}', // optional and current one is default format that will be logged
            'handlers' =>
                [
                    'main'   =>
                        [
                            'type'   => 'stream',
                            'path'   => "data/main.log",
                            'level'  => Logger::DEBUG,
                            'bubble' => true,
                        ],
                ],
        ],
];
```

Please refer to Loggables list at end for all possible variables.

##### 3) Add factory and middleware to `dependencies.global.php` file as follows:

[](#3-add-factory-and-middleware-to-dependenciesglobalphp-file-as-follows)

```
'factories' => [

            \MonologMiddleware\MonologMiddleware::class => \MonologMiddleware\Factory\MonologMiddlewareFactory::class,
        ],
```

##### 4) Now to start recording logs of request/response for a middleware, just put the following line after routing.

[](#4-now-to-start-recording-logs-of-requestresponse-for-a-middleware-just-put-the-following-line-after-routing)

Example:

```
'routes' => [
        [
            'name' => 'home',
            'path' => '/',
            'middleware' => [
               App\Action\HomePageAction::class,
               \MonologMiddleware\MonologMiddleware::class,
               ],
            'allowed_methods' => ['GET'],
        ],
];
```

Now every time you call the route `/`, you'll get logs for request and response.

**By default, MonologMiddleware will record logs in debug mode. If you want to handle different levels, just change `level` in config.**

### Requirements

[](#requirements)

- PHP &gt;= 7.1

### Configuration examples

[](#configuration-examples)

Full example of each implemented handler in Monolog Middleware. Please note that these might not be ALL handlers supported by Monolog, they are just the implemented in this middleware.

All lines are required unless stated.

##### Stream

[](#stream)

```
$streamHandler = [
'main'   =>
    [
        'type'   => 'stream',
        'path'   => 'data/main.log',
        'level'  => Logger::DEBUG,
        'bubble' => true, // optional
    ],
];
```

##### Loggly

[](#loggly)

```
$logglyHandler = [
'loggly'   =>
    [
        'type'   => 'loggly',
        'token'   => 'your-loggly-token',
        'level'  => Logger::DEBUG,
        'bubble' => true, //optional
    ],
];
```

##### Slack

[](#slack)

```
$slackHandler = [
'slack'   =>
    [
        'type'       => 'slack',
        'token'      => 'your-slack-token',
        'channel'    => '#your-slack-channel',
        'level'      => Logger::DEBUG,
        'icon_emoji' => '::ghost::', // optional
        'bubble'     => true, // optional
    ],
];
```

##### Pushover

[](#pushover)

```
$pushOverHandler = [
'pushover'   =>
    [
        'type'    => 'pushover',
        'token'   => 'your-pushover-token',
        'user'    => 'pushover user',
        'level'   => Logger::ERROR,
        'title'   => 'Log title', // optional
        'bubble'  => true, // optional
    ],
];
```

##### Native Email handler

[](#native-email-handler)

```
$nativeEmailHandler = [
'native_email'   =>
    [
        'type'             => 'native_email',
        'level'            => Logger::CRITICAL,
        'from_email'       => 'logs@yourserver.com',
        'to_email'         => 'email@email.com',
        'subject'          => 'Email subject', // optional
        'max_column_width' => 70, //optional
        'bubble'           => true, // optional
    ],
];
```

##### Browser Console handler

[](#browser-console-handler)

```
$browserConsoleHandler = [
'browser_console'   =>
    [
        'type'    => 'browser_console',
        'level'   => Logger::DEBUG,
    ],
];
```

##### Redis handler

[](#redis-handler)

```
$redisHandler = [
'redis'   =>
    [
        'type'          => 'redis',
        'level'         => Logger::DEBUG,
        'redis_client'  => new \Redis(),
        'key'           => 'monolog',
    ],
];
```

##### FirePHP handler

[](#firephp-handler)

```
$redisHandler = [
'firephp'   =>
    [
        'type'          => 'firephp',
        'level'         => Logger::DEBUG,
    ],
];
```

##### NewRelic handler

[](#newrelic-handler)

```
$redisHandler = [
'new_relic'   =>
    [
        'type'          => 'new_relic',
        'level'         => Logger::DEBUG,
        'app_name'      => 'Monolog', // optional
    ],
];
```

#### Loggables list

[](#loggables-list)

To log request/response body you can use `{req_body}` and `{res_body}` respectively in `format` setting.

Full list of logs variables with description:

VariableSubstitution{request}Full HTTP request message{response}Full HTTP response message{ts}Timestamp{host}Host of the request{method}Method of the request{url}URL of the request{host}Host of the request{protocol}Request protocol{version}Protocol version{resource}Resource of the request (path + query + fragment){port}Port of the request{hostname}Hostname of the machine that sent the request{code}Status code of the response (if available){phrase}Reason phrase of the response (if available){curl\_error}Curl error message (if available){curl\_code}Curl error code (if available){curl\_stderr}Curl standard error (if available){connect\_time}Time in seconds it took to establish the connection (if available){total\_time}Total transaction time in seconds for last transfer (if available){req\_header\_\*}Replace \* with the lowercased name of a request header to add to the message{res\_header\_\*}Replace \* with the lowercased name of a response header to add to the message{req\_body}Request body{res\_body}Response body#### Extending Middleware

[](#extending-middleware)

To extend the middleware to log your own format, or specific data like cookies, server params .. etc. You can do that easily using the following steps:

1. Create a factory class. I have named it `MyMonologMiddlewareFactory` which will call a `MyMonologMiddleware` class which will be your customised middleware to log.

```
class MyMonologMiddlewareFactory
{

    /**
     * @param ContainerInterface $serviceContainer
     * @return MonologMiddleware
     * @throws MonologConfigException
     */
    public function __invoke(ContainerInterface $serviceContainer)
    {
        $config = $serviceContainer->get('config');
        if (null === $config) {
            throw new MonologConfigException("Can not find monolog configuration in your config. Make sure to have monolog configuration array in your config");
        }

        $helper = new MonologConfigurationExtension($config['monolog']);
        $logHandlers = $helper->getLogHandlers();
        $loggerName = (isset($config['monolog']['logger_name']) ? $config['monolog']['logger_name'] : 'monolog');
        /**
         * @var Logger
         */
        $monologLogger = new Logger($loggerName);
        $monologLogger->setHandlers($logHandlers);

        return new MyMonologMiddleware($monologLogger);
    }
}
```

2. Create Middleware class

```
class MonologMiddleware implements MiddlewareInterface
{
    /**
     * @var Logger
     */
    protected $logger;

    /**
     * MonologMiddleware constructor.
     * @param Logger $logger
     */
    public function __construct(Logger $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @param callable $next
     * @return mixed
     */
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
    {
        // Here you set logger level, message or any data that you'd like from your request or response.
        // For example, I am going to log cookie params

        $this->logger->addInfo(Logger::INFO, implode(", ", $request->getCookieParams());
        return $next($request, $response);
    }

}
```

3. Add your factory and middleware to global dependency file. Assuming you have your middleware and factory in the same directory, the config will be:

```
    'factories' => [
            MyMonologMiddleware::class => MyMonologMiddlewareFactory::class,
    ],
```

That's it ... you're ready to use your own customised logger.

> Monolog Middleware was written during my commute time. Written with passion on SouthWest Trains. **Please mind the gap!**

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity33

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 78.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~93 days

Total

8

Last Release

2980d ago

Major Versions

0.4 → 1.02017-03-15

v1.1.4 → v2.0.02017-05-03

v2.0.0 → v3.0.02018-03-22

PHP version history (2 changes)0.1PHP ^5.5 || ^7.0

v3.0.0PHP ^7.1 || ^7.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/a37c485c4c88bba79dcff5c59c0868ce8d48bfa6d1bc693b0e8050eeb0cc12ec?d=identicon)[orasik](/maintainers/orasik)

---

Top Contributors

[![orasik](https://avatars.githubusercontent.com/u/9113844?v=4)](https://github.com/orasik "orasik (26 commits)")[![skunde](https://avatars.githubusercontent.com/u/30318390?v=4)](https://github.com/skunde "skunde (5 commits)")[![igor-ciobanu](https://avatars.githubusercontent.com/u/3320786?v=4)](https://github.com/igor-ciobanu "igor-ciobanu (1 commits)")[![oqq](https://avatars.githubusercontent.com/u/7161145?v=4)](https://github.com/oqq "oqq (1 commits)")

---

Tags

middlewaremonolog-middlewarezezend-expressive

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/oras-monolog-middleware/health.svg)

```
[![Health](https://phpackages.com/badges/oras-monolog-middleware/health.svg)](https://phpackages.com/packages/oras-monolog-middleware)
```

###  Alternatives

[silverstripe/framework

The SilverStripe framework

7213.5M2.5k](/packages/silverstripe-framework)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[contao/core-bundle

Contao Open Source CMS

1231.6M2.4k](/packages/contao-core-bundle)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

595.2M386](/packages/shopware-core)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[neos/flow-development-collection

Flow packages in a joined repository for pull requests.

144179.3k3](/packages/neos-flow-development-collection)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
