Laravel 5.6 aws cloudwatch log



将 laravel从 5.4 升级到 5.6。 Laravel从5.6版本开始删除$app->configureMonolog使用

来自 AWS 的教程不再适用。 https://aws.amazon.com/tw/blogs/developer/php-application-logging-with-amazon-cloudwatch-logs-and-monolog/

任何人都可以建议我在哪里迁移$app>配置MonologUsing中的逻辑?

谢谢

使用以下命令安装最新版本的 CloudWatch 处理程序库:

composer require maxbanton/cwh

您可以在config/logging.php中添加custom通道,如下所示:

'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')
],

工厂类App/Logging/CloudWatchLoggerFactory.php为:

<?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;
}
}

如果您在 AWS ECS 上使用 Laravel。

.env文件中添加此LOG_CHANNEL=stderr

它会在您配置任务定义时将日志写入 CloudWatch。

如果您在 AWS EC2 实例上运行并记录大量信息/调试消息,则实时发送日志可能会减慢应用程序响应时间。相反,您可以让 CloudWatch 代理监视您的 laravel.log以发送新的日志条目,即每 5 秒发送一次。CloudWatch 代理可以传送您的所有系统日志和任何系统指标(如 CPU(,以便您可以创建云监视警报。

云观察代理

我想分享我为 Laravel和 Nginx 日志实现 Cloudwatch 的经验。本指南将与使用 Elastic Beanstalk 的多容器 Docker 环境相关。我的方法更多地与流式传输日志相关,而不是手动添加它们。

以下是步骤:

1.

添加.ebextensions/1_cloudwatch.config包含以下内容的文件:

option_settings:
- namespace: aws:elasticbeanstalk:cloudwatch:logs
option_name: StreamLogs
value: true

这将打开默认实例日志流式处理(根据文档(。

阿拉伯数字。

添加.ebextensions/2_logs_streamtocloudwatch_linux.config包含以下内容的文件:

###################################################################################################
#### The following file installs and configures the AWS CloudWatch Logs agent to push logs to a Log
#### Group in CloudWatch Logs.
#### 
#### The configuration below sets the logs to be pushed, the Log Group name to push the logs to and
#### the Log Stream name as the instance id. The following files are examples of logs that will be
#### streamed to CloudWatch Logs in near real time:
#### 
#### 
#### You can then access the CloudWatch Logs by accessing the AWS CloudWatch Console and clicking
#### the "Logs" link on the left. The Log Group name will follow this format:
####
#### /aws/elasticbeanstalk/<environment name>/<full log name path>
####
#### Please note this configuration can be used additionally to the "Log Streaming" feature:
#### http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/AWSHowTo.cloudwatchlogs.html
###################################################################################################
packages:
yum:
awslogs: []
files:
"/etc/awslogs/awscli.conf" :
mode: "000600"
owner: root
group: root
content: |
[plugins]
cwlogs = cwlogs
[default]
region = `{"Ref":"AWS::Region"}`
"/etc/awslogs/awslogs.conf" :
mode: "000600"
owner: root
group: root
content: |
[general]
state_file = /var/lib/awslogs/agent-state
"/etc/awslogs/config/logs.conf" :
mode: "000600"
owner: root
group: root
content: |
[/var/log/nginx/error]
log_group_name = `{"Fn::Join":["/", ["/aws/elasticbeanstalk", { "Ref":"AWSEBEnvironmentName" }, "var/log/nginx-error"]]}`
log_stream_name = logs
timestamp_format = '[%d/%b/%Y:%H:%M:%S %z]'
file = /var/log/nginx/error.log
buffer_duration = 5000
use_gzip_http_content_encoding = true
[/var/log/nginx/access]
log_group_name = `{"Fn::Join":["/", ["/aws/elasticbeanstalk", { "Ref":"AWSEBEnvironmentName" }, "var/log/nginx-access"]]}`
log_stream_name = logs
timestamp_format = '[%d/%b/%Y:%H:%M:%S %z]'
file = /var/log/nginx/access.log
buffer_duration = 5000
use_gzip_http_content_encoding = true
[/var/log/nginx/laravel]
datetime_format = %Y-%m-%d %H:%M:%S
log_group_name = `{"Fn::Join":["/", ["/aws/elasticbeanstalk", { "Ref":"AWSEBEnvironmentName" }, "var/log/laravel"]]}`
log_stream_name = logs
timestamp_format = '[%Y-%m-%d %H:%M:%S]'
file = /var/log/laravel/laravel-*.log
buffer_duration = 5000
use_gzip_http_content_encoding = true
multi_line_start_pattern = {datetime_format}
commands:
"01":
command: chkconfig awslogs on
"02":
command: service awslogs restart

此脚本由亚马逊提供,这里是来源 - https://github.com/awsdocs/elastic-beanstalk-samples/blob/master/configuration-files/aws-provided/instance-configuration/logs-streamtocloudwatch-linux.config

这里最有趣的部分是这个:

[/var/log/laravel]
datetime_format = %Y-%m-%d %H:%M:%S
log_group_name = `{"Fn::Join":["/", ["/aws/elasticbeanstalk", { "Ref":"AWSEBEnvironmentName" }, "var/log/laravel"]]}`
log_stream_name = logs
timestamp_format = '[%Y-%m-%d %H:%M:%S]'
file = /var/log/laravel/laravel-*.log
buffer_duration = 5000
use_gzip_http_content_encoding = true
multi_line_start_pattern = {datetime_format}

这些是我们用于Laravel日志记录的参数。这里没什么特别的。

  • log_group_name - 云监视日志组名称,您可以在此处设置一些简单的东西,例如:production-laravel
  • log_stream_name - 组流的名称,您可以在此处设置任何字符串,也可以传递这些"变量":{instance_id},{主机名},{ip_address}而不是静态字符串
  • multi_line_start_pattern = {datetime_format} - 我们需要它来防止从我们的日志文件中为每一行创建新的日志记录

您可以在 CloudWatch 代理参考 - https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/AgentReference.html

3.

我们需要更新我们的Dockerrun.aws.json.

在"volumes"部分中,您需要添加以下项目:

"volumes": [
...
{
"name": "awseb-logs-nginx-proxy",
"host": {
"sourcePath": "/var/log/nginx"
}
},
{
"name": "laravel-logs",
"host": {
"sourcePath": "/var/log/laravel"
}
}
...
]

其次,我们需要更新我们的containerDefinitions部分并为所需的容器添加mountPoints,如下所示:

"containerDefinitions": [
...
{
"name": "laravel-app",
"image": "laravel-image",
"hostname": "laravel",            
"essential": true,
"memory": 256,
"mountPoints": [
{
"sourceVolume": "laravel-logs",
"containerPath": "/var/www/storage/logs"
}
]    
},
{
"name": "nginx",
"image": "nginx-image",
"hostname": "nginx",
"essential": true,
"memory": 128,
"volumesFrom": [
{
"sourceContainer": "app"
}
],
"portMappings": [
{
"hostPort": 80,
"containerPort": 80
}
],
"mountPoints": [
{
"sourceVolume": "awseb-logs-nginx-proxy",
"containerPath": "/var/log/nginx"
}
],
"links": ["laravel-app"]
}
...
]

因此,您的Dockerrun.aws.json文件可能如下所示:

{
"AWSEBDockerrunVersion": 2,
"volumes": [
{
"name": "awseb-logs-nginx-proxy",
"host": {
"sourcePath": "/var/log/nginx"
}
},
{
"name": "laravel-logs",
"host": {
"sourcePath": "/var/log/laravel"
}
}
],
"containerDefinitions": [
{
"name": "laravel-app",
"image": "laravel-image",
"hostname": "laravel",            
"essential": true,
"memory": 256,
"mountPoints": [
{
"sourceVolume": "laravel-logs",
"containerPath": "/var/www/storage/logs"
}
] 
},
{
"name": "nginx",
"image": "nginx-image",
"hostname": "nginx",
"essential": true,
"memory": 128,
"volumesFrom": [
{
"sourceContainer": "app"
}
],
"portMappings": [
{
"hostPort": 80,
"containerPort": 80
}
],
"mountPoints": [
{
"sourceVolume": "awseb-logs-nginx-proxy",
"containerPath": "/var/log/nginx"
}
],
"links": ["laravel-app"]
}        
]    
}

4.

您需要检查是否允许您的 IAM 实例配置文件角色向 CloudWatch 添加日志。默认情况下,角色的名称为aws-elasticbeanstalk-ec2-role,但您可以在环境的"配置"页上的"安全"部分下进行检查。

以下是您需要添加的策略(来源(:

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
"logs:DescribeLogStreams"
],
"Resource": [
"arn:aws:logs:*:*:*"
]
}
]
}

或者,您可以添加仅用于测试CloudWatchLogsFullAccess策略。


因此,您将收到如下日志组:

/
  • aws/elasticbeanstalk/your-env-name/var/log/laravel
  • /
  • aws/elasticbeanstalk/your-env-name/var/log/nginx-access
  • /
  • aws/elasticbeanstalk/your-env-name/var/log/nginx-error

最新更新