Laravel Vapor自定义日志以JSON形式记录到Amazon AWS Cloudwatch


默认情况下,Laravel Vapor将laravel.log文件推送到strerr输出。这是Lambda捡起来扔给Cloudwatch的。除非您通过Vapor UI查看,否则很难浏览。寻找一种简单的方法来做到这一点,并将它们直接推送到Cloudwatch(带有多个文件)。

首先添加了这个很棒的库

composer require maxbanton/cwh 

然后将其添加到日志配置中。。。

'cloudwatch' => [
'driver' => 'custom',
'via' => AppLoggingCloudWatchLoggerFactory::class,
'formatter' => MonologFormatterJsonFormatter::class,
'cloudwatch_stream_name' => 'laravel',
'sdk' => [
'region' => 'eu-west-1',
'version' => 'latest',
'credentials' => [
'key' => env('AWS_CW_ACCESS'),
'secret' => env('AWS_CW_SECRET')
]
],
'retention' => 730,
'level' => 'debug',
],

您需要为具有Cloudwatch访问权限的IAM用户添加AWS_CW_ACCESSAWS_CW_SECRET密钥。

然后添加App/Logging/CloudWatchLoggerFactory.php,内容如下。。

<?php
namespace AppLogging;
use AwsCloudWatchLogsCloudWatchLogsClient;
use MaxbantonCwhHandlerCloudWatch;
use MonologFormatterJsonFormatter;
use MonologLogger;
class CloudWatchLoggerFactory
{
/**
* Create a custom Monolog instance.
*
* @param  array  $config
* @return MonologLogger
*/
public function __invoke(array $config)
{
$sdkParams = $config["sdk"];
$tags = $config["tags"] ?? [ ];
$name = $config["name"] ?? 'cloudwatch';

// Instantiate AWS SDK CloudWatch Logs Client
$client = new CloudWatchLogsClient($sdkParams);

// Log group name, will be created if none
$groupName = config('app.name') . '-' . config('app.env');
// Log stream name, will be created if none
// $streamName = config('app.hostname');
$streamName = $config["cloudwatch_stream_name"];
// Days to keep logs, 14 by default. Set to `null` to allow indefinite retention.
$retentionDays = $config["retention"];
// Instantiate handler (tags are optional)
$handler = new CloudWatch($client, $groupName, $streamName, $retentionDays, 10000, $tags);
$handler->setFormatter(new JsonFormatter());
// Create a log channel
$logger = new Logger($name);
// Set handler
$logger->pushHandler($handler);
//$logger->pushProcessor(new CompanyLogProcessor()); //Use this if you want to adjust the JSON output using a log processor
return $logger;
}
}

然后,您可以将其用作任何日志。。。即Log::channel('cloudwatch')->info('hey');

要强制将默认的laravel.log显示在这里并显示在蒸汽中,只需将其添加为堆栈

'vapor' => [
'driver' => 'stack',
'channels' => ['stderr', 'cloudwatch'],
'ignore_exceptions' => false,
],

然后在环境变量中将logging.default设置设置为vapor

如果您想要额外的日志记录通道,只需将cloudwatch通道设置复制为一个新通道,并确保调整了cloudwatch_stream_name

感谢我在Stackoverflow上找到的另一个答案帮助我到达这里。我想直接在Laravel Vapor的答案下记录这一点,因为我想很多其他人会在尝试这样做时陷入困境!

最新更新