Skip to content

Commit

Permalink
Merge pull request #7 from skunde/feature/upgrade_to_ze3_compatibility
Browse files Browse the repository at this point in the history
Zend Expressive 3 compatibility
  • Loading branch information
orasik authored Mar 22, 2018
2 parents ea42f59 + 7e5febb commit 6772b01
Show file tree
Hide file tree
Showing 25 changed files with 176 additions and 150 deletions.
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
language: php
php:
- 5.6
- 7.0
- 7.1
- 7.2

before_install:
- echo "extension=redis.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini
Expand Down
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@
# Monolog Logger Middleware
Monolog Middleware to be used with PSR-7 middleware frameworks like Zend Expressive and Slim.

**Now it does support Zend Expressive `2.*`**
**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.
Expand Down Expand Up @@ -82,7 +83,7 @@ Please refer to Loggables list at end for all possible variables.


### Requirements
- PHP > 5.5
- PHP >= 7.1


### Configuration examples
Expand Down
14 changes: 8 additions & 6 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,19 @@
}
],
"require": {
"php": "^5.5 || ^7.0",
"php": "^7.1 || ^7.2",
"monolog/monolog": "^1.19",
"psr/http-message": "~1.0.0",
"zendframework/zend-stratigility": "^2",
"container-interop/container-interop": "^1.1",
"symfony/http-foundation": "^3.0",
"guzzlehttp/psr7": "^1.3 || ^1.4"
"guzzlehttp/psr7": "^1.3 || ^1.4",
"psr/http-server-middleware": "^1.0",
"psr/container": "^1.0",
"zendframework/zend-stratigility": "^3.0",
"roave/security-advisories": "dev-master"
},
"require-dev": {
"phpunit/phpunit": "^4.8",
"squizlabs/php_codesniffer": "^2.3"
"squizlabs/php_codesniffer": "^2.3",
"phpunit/phpunit": "^7.0"
},
"autoload": {
"psr-4": {
Expand Down
59 changes: 35 additions & 24 deletions src/MonologMiddleware/Extension/MonologConfigurationExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,19 @@ class MonologConfigurationExtension
* MonologConfigurationExtension constructor.
* This will get the configuration array from Service Container
* @param array $config
* @throws MonologConfigException
*/
public function __construct($config)
{
$this->config = $config;
$this->validate();
}

public function validate()
/**
* @return bool
* @throws MonologConfigException
*/
public function validate(): bool
{
return $this->hasHandlersConfig();
}
Expand All @@ -50,21 +55,23 @@ public function validate()
* @return bool
* @throws MonologConfigException
*/
public function hasHandlersConfig()
public function hasHandlersConfig(): bool
{
if (isset($this->config['handlers'])) {
return true;
} else {
throw new MonologConfigException("Can not find monolog handlers in your config. Make sure to have monolog configuration array in your config");
}

throw new MonologConfigException("Can not find monolog handlers in your config. Make sure to have monolog configuration array in your config");
}

/**
* @return array
* @throws MonologConfigException
* @throws MonologHandlerNotImplementedException
* @throws \Exception
* @throws \Monolog\Handler\MissingExtensionException
*/
public function getLogHandlers()
public function getLogHandlers(): array
{
$handlers = [];
foreach ($this->config['handlers'] as $key => $value) {
Expand All @@ -76,18 +83,22 @@ public function getLogHandlers()

/**
* @param string $name
* @param array $handlerConfig
* @return SlackHandler|StreamHandler
* @param array $handlerConfig
* @return BrowserConsoleHandler|ChromePHPHandler|FirePHPHandler|LogglyHandler|NativeMailerHandler|NewRelicHandler|PushoverHandler|RedisHandler|SlackHandler|StreamHandler
* @throws \LogicException
* @throws \InvalidArgumentException
* @throws MonologConfigException
* @throws MonologHandlerNotImplementedException
* @throws \Exception
* @throws \Monolog\Handler\MissingExtensionException
*/
public function getHandler($name, $handlerConfig)
{
if (!isset($handlerConfig['type'])) {
throw new MonologConfigException(sprintf("Hander %s does not have type", $name));
}

$bubble = (isset($handlerConfig['bubble']) ? $handlerConfig['bubble'] : true);
$bubble = ($handlerConfig['bubble'] ?? true);

switch ($handlerConfig['type']) {
case 'stream':
Expand All @@ -96,8 +107,8 @@ public function getHandler($name, $handlerConfig)
*/
$streamHandlerValidator = new Validator\StreamHandlerConfigValidator($handlerConfig);
$streamHandlerValidator->validate();
$filePermission = (isset($handlerConfig['permission']) ? $handlerConfig['permission'] : null);
$useLocking = (isset($handlerConfig['use_locking']) ? $handlerConfig['use_locking'] : false);
$filePermission = ($handlerConfig['permission'] ?? null);
$useLocking = ($handlerConfig['use_locking'] ?? false);

return new StreamHandler($handlerConfig['path'], $handlerConfig['level'], $bubble, $filePermission, $useLocking);
break;
Expand All @@ -109,11 +120,11 @@ public function getHandler($name, $handlerConfig)
$slackHandlerValidator = new Validator\SlackHandlerConfigValidator($handlerConfig);
$slackHandlerValidator->validate();

$username = (isset($handlerConfig['username']) ? $handlerConfig['username'] : 'Monolog');
$useAttachment = (isset($handlerConfig['use_attachment']) ? $handlerConfig['use_attachment'] : true);
$iconEmoji = (isset($handlerConfig['icon_emoji']) ? $handlerConfig['icon_emoji'] : null);
$useShortAttachment = (isset($handlerConfig['useShortAttachment']) ? $handlerConfig['useShortAttachment'] : false);
$includeContextAndExtra = (isset($handlerConfig['includeContextAndExtra']) ? $handlerConfig['includeContextAndExtra'] : false);
$username = ($handlerConfig['username'] ?? 'Monolog');
$useAttachment = ($handlerConfig['use_attachment'] ?? true);
$iconEmoji = ($handlerConfig['icon_emoji'] ?? null);
$useShortAttachment = ($handlerConfig['useShortAttachment'] ?? false);
$includeContextAndExtra = ($handlerConfig['includeContextAndExtra'] ?? false);

return new SlackHandler($handlerConfig['token'], $handlerConfig['channel'], $username, $useAttachment, $iconEmoji, $handlerConfig['level'], $bubble, $useShortAttachment, $includeContextAndExtra);
break;
Expand All @@ -131,7 +142,7 @@ public function getHandler($name, $handlerConfig)
case 'native_mailer':
$nativeMailHandlerValidator = new Validator\NativeMailHandlerConfigValidator($handlerConfig);
$nativeMailHandlerValidator->validate();
$maxColumnWidth = (isset($handlerConfig['max_column_width']) ? $handlerConfig['max_column_width'] : 70);
$maxColumnWidth = ($handlerConfig['max_column_width'] ?? 70);

return new NativeMailerHandler($handlerConfig['to'], $handlerConfig['subject'], $handlerConfig['from'], $handlerConfig['level'], $bubble, $maxColumnWidth);
break;
Expand All @@ -140,7 +151,7 @@ public function getHandler($name, $handlerConfig)
$newRelicHandlerValidator = new Validator\AbstractHandlerConfigValidator($handlerConfig);
$newRelicHandlerValidator->validate();

$appName = (isset($handlerConfig['app_name']) ? $handlerConfig['app_name'] : null);
$appName = ($handlerConfig['app_name'] ?? null);

return new NewRelicHandler($handlerConfig['level'], $bubble, $appName);
break;
Expand All @@ -149,25 +160,25 @@ public function getHandler($name, $handlerConfig)
case 'pushover':
$pushoverHandlerValidator = new Validator\PushoverHandlerConfigValidator($handlerConfig);
$pushoverHandlerValidator->validate();
$title = (isset($handlerConfig['title']) ? $handlerConfig['title'] : null);
$title = ($handlerConfig['title'] ?? null);

return new PushoverHandler($handlerConfig['token'], $handlerConfig['user'], $title, $handlerConfig['level'], $bubble);
break;
case 'redis':
$redisHandlerValidator = new Validator\RedisHandlerConfigValidator($handlerConfig);
$redisHandlerValidator->validate();
$capSize = (isset($handlerConfig['cap_size']) ? $handlerConfig['cap_size'] : false);
$capSize = ($handlerConfig['cap_size'] ?? false);

return new RedisHandler($handlerConfig['redis_client'], $handlerConfig['key'], $bubble, $capSize);
break;
case 'rotating_file':

$rotatingFileHanlderValidator = new Validator\StreamHandlerConfigValidator($handlerConfig);
$rotatingFileHanlderValidator->validate();
$maxFiles = (isset($handlerConfig['max_files']) ? $handlerConfig['max_files'] : 0);
$filePermission = (isset($handlerConfig['file_permission']) ? $handlerConfig['file_permission'] : null);
$filenameFormat = (isset($handlerConfig['filename_format']) ? $handlerConfig['filename_format'] : '{filename}-{date}');
$dateFormat = (isset($handlerConfig['date_format']) ? $handlerConfig['date_format'] : 'Y-m-d');
$maxFiles = ($handlerConfig['max_files'] ?? 0);
$filePermission = ($handlerConfig['file_permission'] ?? null);
$filenameFormat = ($handlerConfig['filename_format'] ?? '{filename}-{date}');
$dateFormat = ($handlerConfig['date_format'] ?? 'Y-m-d');

$rotatingFileHandler = new RotatingFileHandler($handlerConfig['filename'], $maxFiles, $handlerConfig['level'], $bubble, $filePermission, false);
$rotatingFileHandler->setFilenameFormat($filenameFormat, $dateFormat);
Expand Down Expand Up @@ -208,4 +219,4 @@ public function getHandler($name, $handlerConfig)
}
}

}
}
13 changes: 9 additions & 4 deletions src/MonologMiddleware/Factory/MonologMiddlewareFactory.php
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
<?php
namespace MonologMiddleware\Factory;

use Interop\Container\ContainerInterface;
use Monolog\Logger;
use MonologMiddleware\Exception\MonologConfigException;
use MonologMiddleware\Extension\MonologConfigurationExtension;
use MonologMiddleware\Loggable\LoggableProvider;
use MonologMiddleware\MonologMiddleware;
use Psr\Container\ContainerInterface;

/**
* Class MonologMiddlewareFactory
Expand All @@ -19,6 +19,11 @@ class MonologMiddlewareFactory
* @param ContainerInterface $serviceContainer
* @return MonologMiddleware
* @throws MonologConfigException
* @throws \Exception
* @throws \MonologMiddleware\Exception\MonologHandlerNotImplementedException
* @throws \Monolog\Handler\MissingExtensionException
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
*/
public function __invoke(ContainerInterface $serviceContainer)
{
Expand All @@ -29,8 +34,8 @@ public function __invoke(ContainerInterface $serviceContainer)

$helper = new MonologConfigurationExtension($config['monolog']);
$logHandlers = $helper->getLogHandlers();
$loggerName = (isset($config['monolog']['logger_name']) ? $config['monolog']['logger_name'] : 'monolog');
$loggables = (isset($config['monolog']['loggables']) ? $config['monolog']['loggables'] : null);
$loggerName = ($config['monolog']['logger_name'] ?? 'monolog');
$loggables = ($config['monolog']['loggables'] ?? null);

$loggableProvider = new LoggableProvider($loggables);

Expand All @@ -42,4 +47,4 @@ public function __invoke(ContainerInterface $serviceContainer)

return new MonologMiddleware($monologLogger, $loggableProvider);
}
}
}
5 changes: 3 additions & 2 deletions src/MonologMiddleware/Loggable/LoggableProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ public function format(
RequestInterface $request,
ResponseInterface $response = null,
\Exception $error = null
) {
): string
{
$cache = [];

return preg_replace_callback(
Expand Down Expand Up @@ -181,7 +182,7 @@ function (array $matches) use ($request, $response, $error, &$cache) {
* @param MessageInterface $message
* @return string
*/
private function headers(MessageInterface $message)
private function headers(MessageInterface $message): string
{
$result = '';
foreach ($message->getHeaders() as $name => $values) {
Expand Down
21 changes: 13 additions & 8 deletions src/MonologMiddleware/MonologMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@

namespace MonologMiddleware;

use Interop\Http\ServerMiddleware\DelegateInterface;
use Interop\Http\ServerMiddleware\MiddlewareInterface;
use Monolog\Logger;
use MonologMiddleware\Loggable\LoggableData;
use MonologMiddleware\Loggable\LoggableProvider;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Symfony\Component\HttpFoundation\Response;

/**
Expand All @@ -29,17 +28,23 @@ class MonologMiddleware implements MiddlewareInterface

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

public function process(ServerRequestInterface $request, DelegateInterface $delegate)
/**
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
* @return ResponseInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$response = $delegate->process($request);
$response = $handler->handle($request);
$level = $this->getLogLevel($response->getStatusCode());

$this->log($level, $request, $response);
Expand All @@ -51,7 +56,7 @@ public function process(ServerRequestInterface $request, DelegateInterface $dele
* @param int $responseCode
* @return int
*/
public function getLogLevel($responseCode)
public function getLogLevel($responseCode): int
{
// Log level will be dependant on Response Code
switch ($responseCode) {
Expand Down Expand Up @@ -84,7 +89,7 @@ public function getLogLevel($responseCode)
* @param ResponseInterface $response
* @return bool
*/
public function log($level, ServerRequestInterface $request, ResponseInterface $response)
public function log($level, ServerRequestInterface $request, ResponseInterface $response): bool
{
return $this->logger->addRecord($level, $this->loggableProvider->format($request, $response));
}
Expand Down
Loading

0 comments on commit 6772b01

Please sign in to comment.