使用laravel 5.5,我们可以访问configureMonologUsing()$ app中的方法,这样就可以在bootstrap/app.php中实现这样的功能:
$app->configureMonologUsing(function (Monolog\Logger $monolog) {
$processUser = posix_getpwuid(posix_geteuid());
$processName= $processUser['name'];
$filename = storage_path('logs/laravel-' . php_sapi_name() . '-' . $processName . '.log');
$handler = new Monolog\Handler\RotatingFileHandler($filename);
$monolog->pushHandler($handler);
});
Run Code Online (Sandbox Code Playgroud)
当您的应用程序可以从具有不同用户(需要)和文件轮换的不同上下文(例如CLI/HTTP)调用时,执行此操作非常有用.执行此操作可防止在HTTP用户创建日志文件之前写入错误,然后CLI会尝试在其中添加内容,反之亦然.
处理这个是非常棘手或不安全的,因为它涉及能够在可能尚不存在的文件上设置写权限.
另外,通过上下文分隔日志非常方便,因为它们通常没什么共同之处,因此可以更容易地在它们之间进行搜索.
不幸的是,使用laravel 5.6不再可能采用这种方式,而且我还没有找到一种方法来透明地执行所有基于文件的日志记录.
谢谢
现在通过为Monolog调用自定义格式化程序来完成自定义.
这是一个使用每日旋转文件名的例子(和我一样).
这可以设置config/logging.php,注意非默认tap参数:
'channels' => [
'daily' => [
'driver' => 'daily',
'tap' => [App\Logging\CustomFilenames::class],
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
],
]
Run Code Online (Sandbox Code Playgroud)
在您的自定义格式化程序中,您可以根据需要操作Monolog记录器,类似于configureMonologUsing():
app\Logging\CustomFilenames.php
<?php
namespace App\Logging;
use Monolog\Handler\RotatingFileHandler;
class CustomFilenames
{
/**
* Customize the given logger instance.
*
* @param \Illuminate\Log\Logger $logger
* @return void
*/
public function __invoke($logger)
{
foreach ($logger->getHandlers() as $handler) {
if ($handler instanceof RotatingFileHandler) {
$sapi = php_sapi_name();
$handler->setFilenameFormat("{filename}-$sapi-{date}", 'Y-m-d');
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
恢复原始行为的一种方法是{date}从处理程序中删除组件filenameFormat.更好的方法可能是操纵single驱动程序的适当处理程序.
请参阅:https://laravel.com/docs/5.6/logging#advanced-monolog-channel-customization
解决方案:
step1:在 config/logging.php 文件中创建一个频道
例子 :
'channels' => [
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
],
'web' => [
'driver' => 'single',
'path' => storage_path('logs/web/web.log'),
],
]
Run Code Online (Sandbox Code Playgroud)
步骤 2:现在从控制器设置动态路径,如下所示
config(['logging.channels.web.path' => storage_path('logs/web/'.time().'.log')]);
Run Code Online (Sandbox Code Playgroud)
第3步:现在生成您的日志
Log::channel('web')->info("your message goes here");
Run Code Online (Sandbox Code Playgroud)
享受 :)