Lumen 实现自定义LOG目录

问题背景:

Lumen 的runtime Log 默认保存在项目目录 storage/logs/lumen.log

由于对写日志这种有要求,必须放到项目之外怎么办?

想这么做也很简单,写几行代码 就可以了。

查看源码,找到Log是如何注册的。

vendor/laravel/lumen-framework/src/Application.php 中的代码如下:

<?php

namespace Laravel\Lumen;

class Application extends Container
{

    // ... 
    /**
     * Register container bindings for the application.
     *
     * @return void
     */
    protected function registerLogBindings()
    {
        $this->singleton('Psr\Log\LoggerInterface', function () {
            if ($this->monologConfigurator) {
                return call_user_func($this->monologConfigurator, new Logger('lumen'));
            } else {
                return new Logger('lumen', [$this->getMonologHandler()]);
            }
        });
    }

    
    /**
     * Get the Monolog handler for the application.
     *
     * @return \Monolog\Handler\AbstractHandler
     */
    protected function getMonologHandler()
    {
        return (new StreamHandler(storage_path('logs/lumen.log'), Logger::DEBUG))
                            ->setFormatter(new LineFormatter(null, null, true, true));
    }
    
    // ...
}

好了, 看来只要修改getMonologHandler()就可以了。

本着面向对象的思路,面向接口和配置编程,决定不改源码,用继承的方式来扩展我们的功能。

添加代码 app/Applicaiton.php

<?php

/**
 *
 * 自定义Application 实现自定义LOG目录
 * lumen log配置在 .env  env('APP_LOG_PATH')
 */
namespace App;

use Laravel\Lumen\Application as LumenApplication;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

class Application extends LumenApplication
{

    /**
     * Create a new Lumen application instance.
     *
     * @param  string|null  $basePath
     * @return void
     */
    public function __construct($basePath = null)
    {
        parent::__construct($basePath);
    }

    /**
     * Get the Monolog handler for the application.
     *
     * @return \Monolog\Handler\AbstractHandler
     */
    protected function getMonologHandler()
    {
        return (new StreamHandler(
            env('APP_LOG_PATH') ? env('APP_LOG_PATH') : storage_path('logs/lumen.log'), 
            Logger::DEBUG))->setFormatter(new LineFormatter(null, null, true, true));
    }
}

修改Lumen要启动的Application实例 bootstrap/app.php

//原来的代码
$app = new Laravel\Lumen\Application(
    realpath(__DIR__.'/../')
);

// 改为 

$app = new App\Application(
    realpath(__DIR__.'/../')
);

不要忘记 .env 中添加配置

.env示例

APP_LOG_PATH=/data/logs/apps/lumen/lumen.log
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容