我正在寻找自定义日志文件名的解决方案。我有一个正在5.6版本项目中工作的解决方案。但是在那之后意味着超过5.6则无法正常工作。我尝试使用许多解决方案,但无法正常工作。每次生成文件名 laravel.log 时。但我想像 laravel- {vendor_code}-{date} .log
我使用了下面的代码的解决方案。
CustomLogFile.php
<?php
namespace App\Logging;
use Illuminate\Http\Request;
use Monolog\Handler\RotatingFileHandler;
class CustomLogFile
{
/**
* Customize the given logger instance.
*
* @param \Illuminate\Log\Logger $logger
* @return void
*/
public function __invoke($logger )
{
$code = 'NA';
$headers = apache_request_headers();
if( isset( $headers['DBAuth'] ))
{
$code = dnc($headers['DBAuth']) ;
}
elseif ( isset($_REQUEST['code']) )
{
$code = $_REQUEST['code'];
}
foreach ($logger->getHandlers() as $handler) {
if ($handler instanceof RotatingFileHandler) {
$sapi = php_sapi_name();
$handler->setFilenameFormat("{filename}-$code-{date}", 'Y-m-d');
}
}
}
}
Config / logging.php
'default' => env('LOG_CHANNEL', 'stack'),
......
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['daily'],
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
],
'daily' => [
'driver' => 'daily',
'tap' => [App\Logging\CustomLogFile::class],
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
'days' => 14,
],
在Laravel的 5.6 v 中,此代码作为我的条件,但不超过 5.6 v 。
我尝试检查 $ logger-> getHandlers()。那么我得到的 stream 数组为空。所以这可能是原因吗?
答案 0 :(得分:1)
这是 Laravel 8 的工作解决方案:
<块引用>CustomLogFile.php
class CustomLogFile
{
public function __invoke(array $config): Logger
{
$log = new Logger($config['logname']);
$level = $log::toMonologLevel($config['level'] ?: 'debug');
$vendor_code = $_REQUEST['code'] ?? 'NA';
$date = Carbon::now()->toDateString();
$logPath = storage_path("logs/$vendor_code-$date.log");
$log->pushHandler(new StreamHandler($logPath, $level, false));
return $log;
}
}
<块引用>
配置/logging.php
'channels' => [
//...
'by_vendor_code' => [
'driver' => 'custom',
'via' => UserLogger::class,
'logname' => 'by_vendor_code',
'level' => 'debug',
],
//...
],
<块引用>
任何地方的使用示例:
logs('by_vendor_code')->info('this vendor want to: ', ['context' => 'some context data']);
答案 1 :(得分:0)
可能是它的答案在 env文件
中是这样的LOG_CHANNEL=daily
LOG_LEVEL=debug
还可以在Config / logging.php中更改日期设置
'daily' => [
'driver' => 'daily',
'tap' => [App\Logging\CustomLogFile::class],
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
'days' => 1, // 14----> 1
因为在6.2版本中我得到了那个结果。所以在这里回答,我会尽快以8. *版本确认。