简体   繁体   English

配置PHP Monolog以通过流登录到Amazon S3

[英]Configure PHP Monolog to log to Amazon S3 via stream

We're using Monolog to log output from our server side PHP worker scripts, that execute on Amazon Elastic Beanstalk EC2 server instances. 我们使用Monolog来记录我们的服务器端PHP工作者脚本的输出,这些脚本在Amazon Elastic Beanstalk EC2服务器实例上执行。 It's rather hard to access log files, especially considering that servers start up and shut down as scaling demand changes. 访问日志文件相当困难,特别是考虑到服务器在扩展需求变化时启动和关闭。

How can I configure Monolog to log directly to an Amazon S3 stream/bucket? 如何配置Monolog以直接登录到Amazon S3流/存储桶?

So far I'm trying something like this in my Pimple dependency injection definitions: 到目前为止,我在我的Pimple依赖注入定义中尝试这样的事情:

$this->container['log'] = function ($c) {
    $logger = new \Monolog\Logger('psd_worker');
    $handler = new \Monolog\Handler\StreamHandler('s3://mybucket/logs/test.log');
    $logger->pushHandler($handler);
    return $logger;
};

but no log file is appearing on the bucket, neither am I getting any exceptions. 但是没有日志文件出现在存储桶上,我也没有得到任何例外。

A little test reveals that I can write through s3:// to the S3 bucket: 一个小测试显示我可以通过s3://写入S3存储桶:

$stream = fopen("s3://{$bucket}/{$key}", 'w');
fwrite($stream, 'Hello S3 World!');
fclose($stream);

but I want Monologs logging functions to write to this bucket. 但我希望Monologs记录功能​​写入此存储桶。

Managed to get it working. 管理以使其工作。 First make an Amazon S3 DI service, making sure to call $s3_client->registerStreamWrapper() : 首先制作一个Amazon S3 DI服务,确保调用$s3_client->registerStreamWrapper()

    $this->container['s3_client'] = function ($c) {
        $s3_client = \Aws\S3\S3Client::factory([
            'key' => Config::get('amazon_s3.key'),
            'secret' => Config::get('amazon_s3.secret')
        ]);
        $s3_client->registerStreamWrapper();
        return $s3_client;
    };

then the logger, which should call s3_client to ensure the stream wrapper registration is made: 然后是记录器,它应调用s3_client以确保进行流包装器注册:

    $this->container['log'] = function ($c) {
        $this->container['s3_client'];

        $logger = new \Monolog\Logger('psd_worker');
        $handler = new \Monolog\Handler\StreamHandler("s3://mybucket/logs/monolog_s3.log");
        $logger->pushHandler($handler);

        return $logger;
    };

Then, when calling the logger's logging methods: 然后,在调用记录器的日志记录方法时:

    $log = $this->container['log'];
    $log->info("Another from Monolog to Amazon S3!!!");

Will result in the data being written to the configured bucket. 将导致数据写入配置的存储桶。 It appears the data is only written when fclose() is called, would be nice to be able to see the log grow live, but I'm guessing that's going to need a socket approach. 看来数据只在调用fclose()时写入,能够看到日志生长会很好,但我猜这需要套接字方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM