简体   繁体   中英

Overriding the log interface container binding lumen 5.0

I am trying to override where lumen writes logs, from 'storage/logs/lumen.log' to 'php://stderr'. The following code is what I am currently trying, and it does not work as expected.

No errors are thrown, and my logs are still written to the default location (in the storage/logs folder).

And when I do:

dd(app('Psr\Log\LoggerInterface'));

I get the default implementation.

Did I misinterpret the documentation, or am I approaching this the wrong way?

<?php namespace App\Providers;

use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Formatter\LineFormatter;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        app()->instance('Psr\Log\LoggerInterface', new Logger('lumen', [$this->getMonologHandler()]));
    }

    public function getMonologHandler() {
        return (new StreamHandler('php://stderr', Logger::DEBUG))->setFormatter(new LineFormatter(null, null, true, true));
    }
}

您需要扩展\\Laravel\\Lumen\\Application并重写registerLogBindings()和/或getMonologHandler()方法来设置您自己的日志记录配置。

Here's a clean solution that doesn't require you to extend the application:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;

class LogServiceProvider extends ServiceProvider
{
    /**
     * Configure logging on boot.
     *
     * @return void
     */
    public function boot()
    {
        $maxFiles = 5;

        $handlers[] = (new RotatingFileHandler(storage_path('logs/lumen.log'), $maxFiles))
            ->setFormatter(new LineFormatter(null, null, true, true));

        $this->app['log']->setHandlers($handlers);
    }

    /**
     * Register the log service.
     *
     * @return void
     */
    public function register()
    {
        // Log binding already registered in vendor/laravel/lumen-framework/src/Application.php.
    }
}

Then don't forget to add the service provider to your Lumen bootstrap/app.php:

$app->register(\App\Providers\LogServiceProvider::class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM