1. Go to this page and download the library: Download oras/monolog-middleware library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
oras / monolog-middleware example snippets
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,
],
],
],
];
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);
}
}
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);
}
}