来自中间件的Slimphp日志

时间:2018-07-30 08:26:02

标签: php slim

我在一个使用Monolog进行日志记录的Slim PHP项目中进行了以下设置,但无法从中间件进行记录。

在Dependdencies.php中,我有

$container['logger'] = function ($c) {
    $settings = $c->get('settings')['logger'];
    $logger = new Monolog\Logger($settings['name']);
    $logger->pushProcessor(new Monolog\Processor\UidProcessor());
    $logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], $settings['level']));
    return $logger;
};

然后在我拥有的middleware.php中

use App\Middleware\Logging;
$app->add(new Logging($container->logger));

使用App \ Middleware \ Logging:

<?php

namespace App\Middleware;

class Logging
{

public function __construct($logger)
{
    $this->logger = $logger;
}

public function __invoke($request, $response, $next)
{
    $routeParams = $request->getAttribute('routeInfo')[2];
    $this->logger->info($request->getMethod() . " -- " . $request->getUri());
    return $next($request, $response);
}
}

然后如何从另一个中间件文件登录?

我也有App / Middleware / CacheMiddleware

<?php

namespace  App\Middleware;

use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

class CacheMiddleware
{
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
{
    //$this->logger->info('test');
    $response->getBody()->write('BEFORE');
    return $next($request, $response);
}
}

但是我收到错误消息Call to a member function info() on null

任何帮助都会很棒。

谢谢

1 个答案:

答案 0 :(得分:0)

在您的代码中,类CacheMiddleware没有成员$logger。在类Logging中,您将记录器实例传递给构造函数,并相应地设置$this->logger,但在CacheMiddleware中,您不需要。
在另一堂课中做同样的事情:

class CacheMiddleware
{

    public function __construct($logger)
        {
            $this->logger = $logger;
        }
    // rest of class definition
}

,当您将CacheMiddleware的新实例添加到应用中间件时,将$container['logger']传递给构造函数,就像使用$app->add(new Logging($container->logger));一样:

$app->add(new CacheMiddleware($container->logger));