Laravel 5.6 aws cloudwatch log
Install the latest version of CloudWatch handler library with:
composer require maxbanton/cwh
You can add a custom
channel in config/logging.php
like:
'cloudwatch' => [
'driver' => 'custom',
'via' => \App\Logging\CloudWatchLoggerFactory::class,
'sdk' => [
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'version' => 'latest',
'credentials' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY')
]
],
'retention' => env('CLOUDWATCH_LOG_RETENTION',7),
'level' => env('CLOUDWATCH_LOG_LEVEL','error')
],
and a factory class App/Logging/CloudWatchLoggerFactory.php
as:
<?php
namespace App\Logging;
use Aws\CloudWatchLogs\CloudWatchLogsClient;
use Maxbanton\Cwh\Handler\CloudWatch;
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');
// 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);
// Create a log channel
$logger = new Logger($name);
// Set handler
$logger->pushHandler($handler);
return $logger;
}
}
IF you are using Laravel on AWS ECS.
Inside .env
file add this LOG_CHANNEL=stderr
It will write logs to CloudWatch when you configure the Task Definition.
If you are running on AWS EC2 instances and log a lot of info / debug messages sending logs real time can slow down your application response times. Instead you can have CloudWatch agent watching your laravel.log to send new log entries in i.e. every 5 seconds. CloudWatch agent can ship all your system logs and any system metrics like CPU so you can create cloud watch alerts.
CloudWatch Agent