如何自定义Laravel 8.0中的日志文件名? [英] how to customize file name of log in Laravel 8.0?
问题描述
我正在寻找自定义日志文件名的解决方案.我有一个正在5.6版本项目中工作的解决方案.但是在那之后意味着超过5.6则无法正常工作.我尝试使用许多解决方案,但无法正常工作.每次生成文件名 laravel.log 时.但我想像 laravel- {vendor_code}-{date} .log
i was searching solution for custom Log file name. i got a solution that was working in 5.6 version project. but after that means more than 5.6 it is not working. i try to used many solution but not working. every time file name generating laravel.log. but i want to get it like laravel-{vendor_code}-{date}.log
我使用了下面的代码的解决方案.
i used solution that code is below.
CustomLogFile.php
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
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 .
here this code is working as my condition in 5.6 v of Laravel but not more than 5.6 v.
我尝试检查 $ logger-> getHandlers().那么我得到的 stream 数组为空.所以这可能是原因吗?
i try to inspect the $logger->getHandlers() . then i am getting stream array is null. so can it be reason of this.
推荐答案
这是Laravel 8的有效解决方案:
Here is working solution for Laravel 8:
CustomLogFile.php
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;
}
}
Config/logging.php
Config/logging.php
'channels' => [
//...
'by_vendor_code' => [
'driver' => 'custom',
'via' => UserLogger::class,
'logname' => 'by_vendor_code',
'level' => 'debug',
],
//...
],
任何地方的用法示例:
Usage example from anywhere:
logs('by_vendor_code')->info('this vendor want to: ', ['context' => 'some context data']);
这篇关于如何自定义Laravel 8.0中的日志文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!