Skip to content
Advertisement

Laravel 5.6 aws cloudwatch log

Upgraded laravel from 5.4 to 5.6. Laravel removed $app->configureMonologUsing since version 5.6

the tutorial from aws not applicable anymore. https://aws.amazon.com/tw/blogs/developer/php-application-logging-with-amazon-cloudwatch-logs-and-monolog/

anyone can advise me where to migrate the logic inside $app->configureMonologUsing ?

thanks

Advertisement

Answer

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' => AppLoggingCloudWatchLoggerFactory::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 AppLogging;

use AwsCloudWatchLogsCloudWatchLogsClient;
use MaxbantonCwhHandlerCloudWatch;
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');

        // 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;
    }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement