{"id":15519388,"url":"https://github.com/orasik/monolog-middleware","last_synced_at":"2025-04-23T03:48:29.348Z","repository":{"id":49867044,"uuid":"60244772","full_name":"orasik/monolog-middleware","owner":"orasik","description":"Monolog middleware for PSR-7 micro frameworks like Zend Expressive and Slim","archived":false,"fork":false,"pushed_at":"2021-06-09T14:47:55.000Z","size":65,"stargazers_count":20,"open_issues_count":1,"forks_count":7,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-04-23T03:48:24.345Z","etag":null,"topics":["middleware","monolog-middleware","ze","zend-expressive"],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/orasik.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-06-02T08:07:07.000Z","updated_at":"2023-06-18T15:53:17.000Z","dependencies_parsed_at":"2022-08-24T00:00:58.802Z","dependency_job_id":null,"html_url":"https://github.com/orasik/monolog-middleware","commit_stats":null,"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/orasik%2Fmonolog-middleware","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/orasik%2Fmonolog-middleware/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/orasik%2Fmonolog-middleware/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/orasik%2Fmonolog-middleware/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/orasik","download_url":"https://codeload.github.com/orasik/monolog-middleware/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250366681,"owners_count":21418768,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["middleware","monolog-middleware","ze","zend-expressive"],"created_at":"2024-10-02T10:21:20.717Z","updated_at":"2025-04-23T03:48:29.315Z","avatar_url":"https://github.com/orasik.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![Build Status](https://travis-ci.org/orasik/monolog-middleware.svg?branch=master)](https://travis-ci.org/orasik/monolog-middleware)\n[![Latest Stable Version](https://poser.pugx.org/oras/monolog-middleware/v/stable)](https://packagist.org/packages/oras/monolog-middleware)\n[![Total Downloads](https://poser.pugx.org/oras/monolog-middleware/downloads)](https://packagist.org/packages/oras/monolog-middleware)\n[![License](https://poser.pugx.org/oras/monolog-middleware/license)](https://packagist.org/packages/oras/monolog-middleware)\n\n# Monolog Logger Middleware\nMonolog Middleware to be used with PSR-7 middleware frameworks like Zend Expressive and Slim.\n\n**Now it does support Zend Expressive `3.*`**\n\nTo use with Zend Expressive `1.*` please install version `1.1.4`\nTo use with Zend Expressive `2.*` please install version `2.0.0`\n\n `loggables` setting inspired by Guzzle Log Format. You can set any data in request/response/headers that you want to log from config file\n rather than in code to give more flexibility in logging more/less data based on your needs.\n\n\n\n### Installation\n\n##### 1) Install middleware using composer\n```sh\ncomposer require oras/monolog-middleware\n```\n##### 2) Add configuration\nThen in your Zend Expressive `config/autoload/` directory, created a new config file call it: `logger.local.php`\n\nAs a starting point, you can have the following in the file:\n\n```php\nuse Monolog\\Logger;\n\nreturn [\n    'monolog' =\u003e\n        [\n            'logger_name' =\u003e 'MyLog',\n            'loggables' =\u003e '[{host}] {request}/{response}', // optional and current one is default format that will be logged\n            'handlers' =\u003e\n                [\n                    'main'   =\u003e\n                        [\n                            'type'   =\u003e 'stream',\n                            'path'   =\u003e \"data/main.log\",\n                            'level'  =\u003e Logger::DEBUG,\n                            'bubble' =\u003e true,\n                        ],\n                ],\n        ],\n];\n```\n\nPlease refer to Loggables list at end for all possible variables.\n\n\n##### 3) Add factory and middleware to `dependencies.global.php` file as follows:\n```php\n'factories' =\u003e [\n\n            \\MonologMiddleware\\MonologMiddleware::class =\u003e \\MonologMiddleware\\Factory\\MonologMiddlewareFactory::class,\n        ],\n```\n\n##### 4) Now to start recording logs of request/response for a middleware, just put the following line after routing.\n\n Example:\n ```php\n 'routes' =\u003e [\n         [\n             'name' =\u003e 'home',\n             'path' =\u003e '/',\n             'middleware' =\u003e [\n                App\\Action\\HomePageAction::class,\n                \\MonologMiddleware\\MonologMiddleware::class,\n                ],\n             'allowed_methods' =\u003e ['GET'],\n         ],\n];\n ```\n\n Now every time you call the route `/`, you'll get logs for request and response.\n\n **By default, MonologMiddleware will record logs in debug mode. If you want to handle different levels, just change `level` in config.**\n\n\n### Requirements\n- PHP \u003e= 7.1\n\n\n### Configuration examples\nFull example of each implemented handler in Monolog Middleware. Please note that these might not be ALL handlers\nsupported by Monolog, they are just the implemented in this middleware.\n\nAll lines are required unless stated.\n\n##### Stream\n```php\n$streamHandler = [\n'main'   =\u003e\n    [\n        'type'   =\u003e 'stream',\n        'path'   =\u003e 'data/main.log',\n        'level'  =\u003e Logger::DEBUG,\n        'bubble' =\u003e true, // optional\n    ],\n];\n```\n\n##### Loggly\n```php\n$logglyHandler = [\n'loggly'   =\u003e\n    [\n        'type'   =\u003e 'loggly',\n        'token'   =\u003e 'your-loggly-token',\n        'level'  =\u003e Logger::DEBUG,\n        'bubble' =\u003e true, //optional\n    ],\n];\n```\n\n##### Slack\n```php\n$slackHandler = [\n'slack'   =\u003e\n    [\n        'type'       =\u003e 'slack',\n        'token'      =\u003e 'your-slack-token',\n        'channel'    =\u003e '#your-slack-channel',\n        'level'      =\u003e Logger::DEBUG,\n        'icon_emoji' =\u003e '::ghost::', // optional\n        'bubble'     =\u003e true, // optional\n    ],\n];\n```\n\n##### Pushover\n```php\n$pushOverHandler = [\n'pushover'   =\u003e\n    [\n        'type'    =\u003e 'pushover',\n        'token'   =\u003e 'your-pushover-token',\n        'user'    =\u003e 'pushover user',\n        'level'   =\u003e Logger::ERROR,\n        'title'   =\u003e 'Log title', // optional\n        'bubble'  =\u003e true, // optional\n    ],\n];\n```\n\n##### Native Email handler\n```php\n$nativeEmailHandler = [\n'native_email'   =\u003e\n    [\n        'type'             =\u003e 'native_email',\n        'level'            =\u003e Logger::CRITICAL,\n        'from_email'       =\u003e 'logs@yourserver.com',\n        'to_email'         =\u003e 'email@email.com',\n        'subject'          =\u003e 'Email subject', // optional\n        'max_column_width' =\u003e 70, //optional\n        'bubble'           =\u003e true, // optional\n    ],\n];\n```\n\n##### Browser Console handler\n```php\n$browserConsoleHandler = [\n'browser_console'   =\u003e\n    [\n        'type'    =\u003e 'browser_console',\n        'level'   =\u003e Logger::DEBUG,\n    ],\n];\n```\n\n##### Redis handler\n```php\n$redisHandler = [\n'redis'   =\u003e\n    [\n        'type'          =\u003e 'redis',\n        'level'         =\u003e Logger::DEBUG,\n        'redis_client'  =\u003e new \\Redis(),\n        'key'           =\u003e 'monolog',\n    ],\n];\n```\n\n##### FirePHP handler\n```php\n$redisHandler = [\n'firephp'   =\u003e\n    [\n        'type'          =\u003e 'firephp',\n        'level'         =\u003e Logger::DEBUG,\n    ],\n];\n```\n\n##### NewRelic handler\n```php\n$redisHandler = [\n'new_relic'   =\u003e\n    [\n        'type'          =\u003e 'new_relic',\n        'level'         =\u003e Logger::DEBUG,\n        'app_name'      =\u003e 'Monolog', // optional\n    ],\n];\n```\n\n\n#### Loggables list\n\nTo log request/response body you can use `{req_body}` and `{res_body}` respectively in `format` setting.\n\nFull list of logs variables with description:\n\n| Variable | \tSubstitution |\n| --- | --- |\n| {request}\t| Full HTTP request message |\n| {response}\t| Full HTTP response message |\n| {ts}\t | Timestamp |\n| {host} |\tHost of the request |\n| {method} |\tMethod of the request |\n| {url}\t | URL of the request |\n| {host} |\tHost of the request |\n| {protocol} | \tRequest protocol |\n| {version} | Protocol version |\n| {resource}|\tResource of the request (path + query + fragment) |\n| {port}\t| Port of the request |\n| {hostname} | \tHostname of the machine that sent the request |\n| {code} | Status code of the response (if available) |\n| {phrase} | Reason phrase of the response (if available) |\n| {curl_error} | Curl error message (if available) |\n| {curl_code} | Curl error code (if available) |\n| {curl_stderr} | Curl standard error (if available) |\n| {connect_time} | Time in seconds it took to establish the connection (if available) |\n| {total_time}\t | Total transaction time in seconds for last transfer (if available) |\n| {req_header_*} | Replace * with the lowercased name of a request header to add to the message |\n| {res_header_*} | Replace * with the lowercased name of a response header to add to the message |\n| {req_body} | Request body  |\n| {res_body} | Response body|\n\n\n\n#### Extending Middleware\n\nTo 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:\n\n1. Create a factory class.\nI have named it `MyMonologMiddlewareFactory` which will call a `MyMonologMiddleware` class which will be your customised middleware to log.\n\n```php\nclass MyMonologMiddlewareFactory\n{\n\n    /**\n     * @param ContainerInterface $serviceContainer\n     * @return MonologMiddleware\n     * @throws MonologConfigException\n     */\n    public function __invoke(ContainerInterface $serviceContainer)\n    {\n        $config = $serviceContainer-\u003eget('config');\n        if (null === $config) {\n            throw new MonologConfigException(\"Can not find monolog configuration in your config. Make sure to have monolog configuration array in your config\");\n        }\n\n        $helper = new MonologConfigurationExtension($config['monolog']);\n        $logHandlers = $helper-\u003egetLogHandlers();\n        $loggerName = (isset($config['monolog']['logger_name']) ? $config['monolog']['logger_name'] : 'monolog');\n        /**\n         * @var Logger\n         */\n        $monologLogger = new Logger($loggerName);\n        $monologLogger-\u003esetHandlers($logHandlers);\n\n        return new MyMonologMiddleware($monologLogger);\n    }\n}\n\n```\n\n2. Create Middleware class\n\n```php\nclass MonologMiddleware implements MiddlewareInterface\n{\n    /**\n     * @var Logger\n     */\n    protected $logger;\n\n    /**\n     * MonologMiddleware constructor.\n     * @param Logger $logger\n     */\n    public function __construct(Logger $logger)\n    {\n        $this-\u003elogger = $logger;\n    }\n\n\n    /**\n     * @param ServerRequestInterface $request\n     * @param ResponseInterface $response\n     * @param callable $next\n     * @return mixed\n     */\n    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)\n    {\n        // Here you set logger level, message or any data that you'd like from your request or response.\n        // For example, I am going to log cookie params\n\n        $this-\u003elogger-\u003eaddInfo(Logger::INFO, implode(\", \", $request-\u003egetCookieParams());\n        return $next($request, $response);\n    }\n\n}\n```\n\n3. Add your factory and middleware to global dependency file. Assuming you have your middleware and factory in the same directory, the config will be:\n\n```php\n    'factories' =\u003e [\n            MyMonologMiddleware::class =\u003e MyMonologMiddlewareFactory::class,\n    ],\n```\n\nThat's it ... you're ready to use your own customised logger.\n\n\n\u003e Monolog Middleware was written  during my commute time. Written with passion on SouthWest Trains. **Please mind the gap!**\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Forasik%2Fmonolog-middleware","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Forasik%2Fmonolog-middleware","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Forasik%2Fmonolog-middleware/lists"}