默认情况下,Laravel Vapor 将laravel.log
文件推送到 strerr 输出。这是 Lambda 拾取并扔给 Cloudwatch 的。除非您通过 Vapor UI 进行查看,否则很难查看。寻找一种简单的方法来执行此操作并将它们直接推送到 Cloudwatch(带有多个文件)。
1 回答
1
首先添加了这个很棒的库
composer require maxbanton/cwh
然后将此添加到您的日志配置中...
'cloudwatch' => [
'driver' => 'custom',
'via' => \App\Logging\CloudWatchLoggerFactory::class,
'formatter' => Monolog\Formatter\JsonFormatter::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_ACCESS
。AWS_CW_SECRET
然后添加App/Logging/CloudWatchLoggerFactory.php
以下内容..
<?php
namespace App\Logging;
use Aws\CloudWatchLogs\CloudWatchLogsClient;
use Maxbanton\Cwh\Handler\CloudWatch;
use Monolog\Formatter\JsonFormatter;
use Monolog\Logger;
class CloudWatchLoggerFactory
{
/**
* Create a custom Monolog instance.
*
* @param array $config
* @return \Monolog\Logger
*/
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 的答案下记录这个,因为我想很多其他人会在尝试这样做时遇到困难!
于 2021-02-12T14:14:58.283 回答