Lumen 实现自定义LOG目录

问题背景:

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

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

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

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

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

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

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

你可能感兴趣的:(Lumen 实现自定义LOG目录)