fei / logger-client

客户端日志记录器

v1.4.2 2020-09-16 13:39 UTC

README

GitHub licensecontinuousphpGitHub issues

安装

只需将以下要求添加到您的 composer.json 文件中

    "fei/logger-client": "^1.2.0"

配置

日志客户端需要一些选项才能正常运行。可以通过 __construct()setOptions() 方法传递给这些选项,包括:

注意: Logger 是 Fei\Service\Logger\Client\Logger 的别名 Notification 是 Fei\Service\Logger\Entity\Notification 的别名

使用方法

初始化

由于日志客户端至少需要一个依赖项(即传输),因此它应该始终由依赖注入组件初始化。此外,BASEURL 参数也应依赖于环境。

// sample configuration for production environment
$logger = new Logger(array(
                            Logger::OPTION_BASEURL  => 'http://logger.flash-global.net',
                            Logger::OPTION_FILTER   => Notification::LVL_DEBUG,
                          )
                    );
// inject transport classes
$logger->setTransport(new BasicTransport());

// optionnal asynchronous transport, that will be automatically used to push notifications
//
// NOTE this transport requires a beanstalk queue able to listen to its requests
$pheanstalk = new Pheanstalk('localhost');
$asyncTransport = new BeanstalkProxyTransport;
$asyncTransport->setPheanstalk($pheanstalk);
$logger->setAsyncTransport($asyncTransport);

推送简单通知

一旦设置了 Logger,您可以通过在 Logger 上调用 notify() 方法来开始推送通知

$logger = $container->get('logger');

$logger->notify('Notification message'); // default level is Notification::LVL_INFO
$logger->notify('Debug message', array('level' => Notification::LVL_DEBUG));

虽然可以通过第二个(数组)参数传递更多内容,但建议不要这样做。如果您想传递更多信息,如上下文,请参阅以下部分。

推送 Notification 实例

推送通知更可靠的方法是自行实例化它,然后通过 notify() 发送,该方法也接受 Notification 实例

$logger = $container->get('logger');

$notification = new Notification(array('message' => 'Notification message'));
$notification
        ->setLevel(Notification::LVL_WARNING)
        ->setContext(array('key' => 'value')
        ;
        
$logger->notify($notification);

PSR-3 适配器

PSR-3 描述了一个用于日志的接口,以确保系统之间的互操作性。

为此,我们提供了适配器 Fei\Service\Logger\Client\Psr\PsrLoggerAdapter

<?php

use Fei\Service\Logger\Client\Logger;
use Fei\Service\Logger\Client\Psr\PsrLoggerAdapter;

$logger = new Logger();

$psr = new PsrLoggerAdapter($logger);

$psr->error('This is a error message');

始终可以使用日志上下文设置类别、命名空间和其他通知属性

<?php

use Fei\Service\Logger\Client\Logger;
use Fei\Service\Logger\Client\Psr\PsrLoggerAdapter;
use Fei\Service\Logger\Entity\Notification;

$logger = new Logger();

$psr = new PsrLoggerAdapter($logger);

$psr->error(
    'This is a error message',
    [
        'namespace' => '/my/app',
        'category' => Notification::TRACKING,
        'key1' => 'value1',
        'key2' => 'value2'
    ]
);

可管理的通知属性包括 flagnamespaceuserservercommandorigincategoryenv。上下文的关键将设置在通知上下文中。