rsalas/cwh

AWS CloudWatch Handler for Monolog 库

v1.0.1 2024-04-10 14:34 UTC

This package is auto-updated.

Last update: 2024-09-10 15:57:07 UTC


README

用于将日志条目发送到 AWS CloudWatch Logs 服务的 PHP 日志库 Monolog 的处理程序。

在开始使用此库之前,建议您了解 AWS CloudWatch 服务的 定价

免责声明

此库通过 AWS PHP SDK 使用 AWS API,它对并发请求有限制。这意味着在高并发或高负载应用程序中,它可能无法以最佳方式工作。请考虑使用其他解决方案,例如使用 fluentd 将日志重定向到 stdout。

要求

  • PHP ^8.0
  • 具有适当权限的 AWS 账户(请参阅以下权限列表)

功能

  • 最多发送 10000 批量日志,以避免 Rate exceeded 错误
  • 使用标签创建日志组
  • AWS CloudWatch Logs 员工懒加载
  • 适用于 Web 应用程序以及长期运行的 CLI 守护进程和工作进程

安装

通过运行以下命令使用 Composer 安装最新版本:

$ composer require rsalas/cwh:^2.0

基本用法

<?php

use Aws\CloudWatchLogs\CloudWatchLogsClient;
use Rsalas\Cwh\Handler\CloudWatch;
use Monolog\Logger;
use Monolog\Formatter\JsonFormatter;

$sdkParams = [
    'region' => 'eu-west-1',
    'version' => 'latest',
    'credentials' => [
        'key' => 'your AWS key',
        'secret' => 'your AWS secret',
        'token' => 'your AWS session token', // token is optional
    ]
];

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

// Log group name, will be created if none
$groupName = 'php-logtest';

// Log stream name, will be created if none
$streamName = 'ec2-instance-1';

// Days to keep logs, 14 by default. Set to `null` to allow indefinite retention.
$retentionDays = 30;

// Instantiate handler (tags are optional)
$handler = new CloudWatch($client, $groupName, $streamName, $retentionDays, 10000, ['my-awesome-tag' => 'tag-value']);

// Optionally set the JsonFormatter to be able to access your log messages in a structured way
$handler->setFormatter(new JsonFormatter());

// Create a log channel
$log = new Logger('name');

// Set handler
$log->pushHandler($handler);

// Add records to the log
$log->debug('Foo');
$log->warning('Bar');
$log->error('Baz');

框架集成

以及其他许多框架

AWS IAM 需要的权限

如果您希望使用单独的程序性 IAM 用户(推荐)或需要定义策略,请确保以下权限包括在内:

  1. CreateLogGroup aws 文档
  2. CreateLogStream aws 文档
  3. PutLogEvents aws 文档
  4. PutRetentionPolicy aws 文档
  5. DescribeLogStreams aws 文档
  6. DescribeLogGroups aws 文档

当将 $createGroup 参数设置为 false 时,可以省略 DescribeLogGroupsCreateLogGroup 权限

AWS IAM 策略完整 JSON 示例

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:DescribeLogGroups"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogStream",
                "logs:DescribeLogStreams",
                "logs:PutRetentionPolicy"
            ],
            "Resource": "{LOG_GROUP_ARN}"
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:PutLogEvents"
            ],
            "Resource": [
                "{LOG_STREAM_1_ARN}",
                "{LOG_STREAM_2_ARN}"
            ]
        }
    ]
}