wshafer/psr11-monolog

此包已被弃用且不再维护。作者建议使用 blazon/psr11-monolog 包。

PSR-11 Monolog 工厂

3.0.0 2019-12-18 22:56 UTC

This package is auto-updated.

Last update: 2021-02-12 20:00:35 UTC


README

codecov Scrutinizer Code Quality Build Status

PSR-11 Monolog

此存储库已迁移且不再维护。请访问新存储库: https://gitlab.com/blazon/psr11-monolog

Monolog 为 PSR-11 提供工厂

目录

安装

composer require wshafer/psr11-monolog

使用方法

<?php

# Get the Channel Changer
$channel = $container->get('my-channel');

# Write to log
$channel->debug('Hi There');

更多详细信息请参阅 文档

容器

任何PSR-11容器都可以使用。为了实现这一点,您需要添加配置并注册一个新的服务,该服务指向WShafer\PSR11MonoLog\MonologFactory

以下是一些具体的容器示例,以帮助您入门

Pimple

// Create Container
$container = new \Xtreamwayz\Pimple\Container([
    // Logger using the default keys.
    'logger' => new \WShafer\PSR11MonoLog\MonologFactory(),
    
    // Another logger using a different channel configuration
    'other' => function($c) {
        return \WShafer\PSR11MonoLog\MonologFactory::channelTwo($c);
    },

    'config' => [
        'monolog' => [
            'handlers' => [
                // At the bare minimum you must include a default handler config.
                // Otherwise log entries will be sent to the void.
                'default' => [
                    'type' => 'stream',
                    'options' => [
                        'stream' => '/var/log/some-log-file.txt',
                    ],
                ],
                
                // Another Handler
                'myOtherHandler' => [
                    'type' => 'stream',
                    'options' => [
                        'stream' => '/var/log/someother-log-file.txt',
                    ],
                ],
            ],
            
            'channels' => [
                // Configure a second channel
                'channelTwo' => [
                    'name' => 'MyOtherChannel',
                    'handlers' => [
                        'myOtherHandler',
                    ],
                ],    
            ],
        ],
    ],
]);

// Get the default channel

/** @var \Monolog\Logger $defaultChannel */
$defaultChannel = $container->get('logger');

// Write to the default channel
$defaultChannel->debug('Write to log');


// Get the second channel

/** @var \Monolog\Logger $channelTwo */
$channelTwo = $container->get('channelTwo');

// Write to the second channel
$channelTwo->debug('Write to log');

Zend Service Manager

<?php
// Create the container and define the services you'd like to use
$container = new \Zend\ServiceManager\ServiceManager([
    'factories' => [
        // Logger using the default keys.
        'logger' => \WShafer\PSR11MonoLog\MonologFactory::class,
        
        // Another logger using a different channel configuration
        'channelTwo' => [\WShafer\PSR11MonoLog\MonologFactory::class, 'channelTwo']
    ]
]);

$container->setService(
    'config',
    [
        'monolog' => [
            'handlers' => [
                // At the bare minimum you must include a default handler config.
                // Otherwise log entries will be sent to the void.
                'default' => [
                    'type' => 'stream',
                    'options' => [
                        'stream' => '/var/log/some-log-file.txt',
                    ],
                ],
                
                // Another Handler
                'myOtherHandler' => [
                    'type' => 'stream',
                    'options' => [
                        'stream' => '/var/log/someother-log-file.txt',
                    ],
                ],
            ],
            
            'channels' => [
                // Configure a second channel
                'channelTwo' => [
                    'name' => 'MyOtherChannel',
                    'handlers' => [
                        'myOtherHandler',
                    ],
                ],    
            ],
        ],
    ]
);

// Get the default channel

/** @var \Monolog\Logger $defaultChannel */
$defaultChannel = $container->get('logger');

// Write to the default channel
$defaultChannel->debug('Write to log');


// Get the second channel

/** @var \Monolog\Logger $channelTwo */
$channelTwo = $container->get('channelTwo');

// Write to the second channel
$channelTwo->debug('Write to log');

框架

任何使用PSR-11的框架都应正常工作。以下是具体的框架示例,以帮助您入门

Zend Expressive

您需要添加配置并注册您想要使用的服务。有多种方法可以实现这一点,但建议的方法是创建一个新的配置文件config/autoload/monolog.global.php

配置

config/autoload/monolog.global.php

<?php
return [
    'dependencies' => [
        'factories' => [
            // Logger using the default keys.
            'logger' => \WShafer\PSR11MonoLog\MonologFactory::class,
            
            // Another logger using a different channel configuration
            'channelTwo' => [\WShafer\PSR11MonoLog\MonologFactory::class, 'channelTwo']
        ]
    ],
    
    'monolog' => [
        'handlers' => [
            // At the bare minimum you must include a default handler config.
            // Otherwise log entries will be sent to the void.
            'default' => [
                'type' => 'stream',
                'options' => [
                    'stream' => '/var/log/some-log-file.txt',
                ],
            ],
            
            // Another Handler
            'myOtherHandler' => [
                'type' => 'stream',
                'options' => [
                    'stream' => '/var/log/someother-log-file.txt',
                ],
            ],
        ],
        
        'channels' => [
            // Configure a second channel
            'channelTwo' => [
                'name' => 'MyOtherChannel',
                'handlers' => [
                    'myOtherHandler',
                ],
            ],    
        ],
    ],
];

Zend Framework 3

您需要添加配置并注册您想要使用的服务。有多种方法可以实现这一点,但建议的方法是创建一个新的配置文件config/autoload/monolog.global.php

配置

config/autoload/monolog.global.php

<?php
return [
    'service_manager' => [
        'factories' => [
            // Logger using the default keys.
            'logger' => \WShafer\PSR11MonoLog\MonologFactory::class,
            
            // Another logger using a different channel configuration
            'channelTwo' => [\WShafer\PSR11MonoLog\MonologFactory::class, 'channelTwo']
        ]
    ],
    
    'monolog' => [
        'handlers' => [
            // At the bare minimum you must include a default handler config.
            // Otherwise log entries will be sent to the void.
            'default' => [
                'type' => 'stream',
                'options' => [
                    'stream' => '/var/log/some-log-file.txt',
                ],
            ],
            
            // Another Handler
            'myOtherHandler' => [
                'type' => 'stream',
                'options' => [
                    'stream' => '/var/log/someother-log-file.txt',
                ],
            ],
        ],
        
        'channels' => [
            // Configure a second channel
            'channelTwo' => [
                'name' => 'MyOtherChannel',
                'handlers' => [
                    'myOtherHandler',
                ],
            ],    
        ],
    ],
];

模块配置

如果您没有使用Zend Component Installer,您还需要注册该模块。

config/modules.config.php (ZF 3 突壳)

<?php

return [
    // ... Previously registered modules here
    'WShafer\\PSR11MonoLog',
];

config/application.config.php (ZF 2 突壳)

<?php

return [
    'modules' => [
        // ... Previously registered modules here
        'WShafer\\PSR11MonoLog',
    ]
];

配置

Monolog使用四种类型的服务,每种服务都需要为您的应用程序进行配置。此外,您还需要根据您使用的容器创建一个命名服务,该服务映射到基于容器的\WShafer\PSR11MonoLog\MonologFactory

  • 命名服务:这些是与工厂连接的服务名称。配置将根据所使用的容器/框架的类型而有所不同。

  • 通道:通道是标识记录与应用程序的哪个部分相关联的绝佳方式。这对于大型应用程序很有用,并且在这里被利用。

    想象两个记录器共享一个写入单个日志文件的处理器。通道允许您识别发布每个记录的记录器。您可以通过过滤这些或那些通道轻松地通过日志文件grep。

  • 处理器:这些服务执行所有繁重的工作并将消息记录到连接的系统。有许多不同的处理器可供您选择,但您最可能想要用于基本文件记录的是StreamHandler提示:您可以为多个通道使用相同的处理器。

  • 格式化程序:(可选)格式化程序负责为处理器格式化消息。通常,您可以使用处理器的默认格式化程序,但在某些情况下,您可能需要更改消息的格式。配置格式化程序将允许您自定义发送到日志的消息。

  • 处理器 : (可选) 处理器可以用来添加数据、更改消息、过滤等。Monolog提供了一些内置处理器,可以在项目中使用。请查看处理器部分以获取列表。

最小配置

最小配置应包括至少一个默认处理器和一个命名服务。请注意,如果您未指定默认处理器,则在连接默认日志记录器时将使用NullHandler

最小示例(使用Zend Expressive作为示例)

<?php

return [
    'dependencies' => [
        'factories' => [
            // Logger using the default keys.
            'logger' => \WShafer\PSR11MonoLog\MonologFactory::class,
        ]
    ],
    
    'monolog' => [
        'handlers' => [
            'default' => [
                'type' => 'stream',
                'options' => [
                    'stream' => '/var/log/some-log-file.txt',
                ],
            ],
        ],
    ],
];

完整配置

完整示例

<?php

return [
    
    'dependencies' => [
        'factories' => [
            // Logger using the default keys.
            'logger' => \WShafer\PSR11MonoLog\MonologFactory::class,
            
            // Another logger using a different channel configuration
            'channelTwo' => [\WShafer\PSR11MonoLog\MonologFactory::class, 'channelTwo']
        ]
    ],
        
    'monolog' => [
        'formatters' => [
            // Array Keys are the names used for the formatters
            'formatterOne' => [
                // A formatter type or pre-configured service from the container
                'type' => 'line',
                
                // Formatter specific options.  See formatters below
                'options' => [
                    'format'                     => "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n",
                    'dateFormat'                 => "c",
                    'allowInlineLineBreaks'      => true,
                    'ignoreEmptyContextAndExtra' => false,
                ],
            ],
            
            'formatterTwo' => [
                // A formatter type or pre-configured service from the container
                'type' => 'line',
                
                // Formatter specific options.  See formatters below
                'options' => [
                    'format'                     => "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n",
                    'dateFormat'                 => "c",
                    'allowInlineLineBreaks'      => false,
                    'ignoreEmptyContextAndExtra' => true,
                ],
            ],
        ],
        
        'handlers' => [
            // Array Keys are the names used for the handlers
            'default' => [
                // A Handler type or pre-configured service from the container
                'type' => 'stream',
                
                // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'formatter' => 'formatterOne', 
                
                // Handler specific options.  See handlers below
                'options' => [
                    'stream' => '/tmp/log_one.txt',
                ], 
                'processors' => [
                    'my-handler-processor',
                ],
            ],
            
            'handlerTwo' => [
                // A Handler type or pre-configured service from the container
                'type' => 'stream', 
                
                // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'formatter' => 'formatterTwo', 
                
                // Adaptor specific options.  See adaptors below
                'options' => [
                    'stream' => '/tmp/log_two.txt',
                ], 
            ],
        ],
        
        'processors' => [
            // Array Keys are the names used for the processors
            'processorOne' => [
                // A processor type or pre-configured service from the container
                'type' => 'psrLogMessage',
                
                // processor specific options.  See processors below
                'options' => [], 
            ],
            
            'processorTwo' => [
                // A processor type or pre-configured service from the container
                'type' => 'uid',
                
                // processor specific options.  See processors below
                'options' => [
                    'length'  => 7,
                ], 
            ],
            'my-handler-processor' => [
                // A processor type or pre-configured service from the container
                'type' => 'psrLogMessage',
                
                // processor specific options.  See processors below
                'options' => [], 
            ],            
        ],
        
        'channels' => [
            // Array Keys are the names used for the channels
            //
            // Note: You can specify "default" here to overwrite the default settings for the
            // default channel.  If no handler is defined for default then the default 
            // handler will be used.
            'default' => [
                // Optional: Name of channel to show in logs.  Defaults to the array key
                'name' => 'MyAppChannel',
                
                // array of handlers to attach to the channel.  Can use multiple handlers if needed.
                'handlers' => ['handlerOne', 'handlerTwo'],
                
                // optional array of processors to attach to the channel.  Can use multiple processors if needed.
                'processors' => ['processorOne', 'processorTwo'],
            ],
            
            'channelTwo' => [
                // Optional: Name of channel to show in logs.  Defaults to the array key
                'name' => 'MyOtherChannel',
                
                // array of handlers to attach to the channel.  Can use multiple handlers if needed.
                'handlers' => ['handlerTwo'],
                
                // optional array of processors to attach to the channel.  Can use multiple processors if needed.
                'processors' => ['processorTwo'],
            ],
        ],
    ],
];

通道

<?php

return [
    'monolog' => [
        'channels' => [
            
            // Array Keys are the channel identifiers
            'myChannelName' => [
                // Optional: Name of channel to show in logs.  Defaults to the array key
                'name' => 'MyChannelLogName',
                                
                // Array of configured handlers.  See handlers for more info
                'handlers' => [  
                    'myHandler',  
                ],
                
                // Array of configured processors.  See processors for more info
                'processors' => [  
                    'myProcessor',  
                ],
            ],
        ],
    ],
];

处理器

记录到文件和syslog

StreamHandler

将日志记录到任何PHP流中,用于日志文件。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'stream',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'stream'         => '/tmp/stream_test.txt', // Required:  File Path | Resource | Service Name
                    'level'          => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'         => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                    'filePermission' => null, // Optional: file permissions (default (0644) are only for owner read/write)
                    'useLocking'     => false, // Optional: Try to lock log file before doing any writes
                ],
            ],
        ],
    ],
];

Monolog 文档: StreamHandler

RotatingFileHandler

将日志记录到文件中,并每天创建一个日志文件。它还将删除超过$maxFiles的文件。尽管如此,您应该使用logrotate进行高配置设置,这只是作为一个快速简便的解决方案。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'rotating',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'filename'       => '/tmp/stream_test.txt', // Required:  File Path
                    'maxFiles'       => 0, // Optional:  The maximal amount of files to keep (0 means unlimited)
                    'level'          => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'         => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                    'filePermission' => null, // Optional: file permissions (default (0644) are only for owner read/write)
                    'useLocking'     => false, // Optional: Try to lock log file before doing any writes
                ],
            ],
        ],
    ],
];

Monolog 文档: RotatingFileHandler

SyslogHandler

将日志记录到syslog中。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'syslog',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'ident'          => '/tmp/stream_test.txt', // Required:  The string ident is added to each message. 
                    'facility'       => LOG_USER, // Optional:  The facility argument is used to specify what type of program is logging the message.
                    'level'          => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'         => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                    'logOpts'        => LOG_PID, // Optional: Option flags for the openlog() call, defaults to LOG_PID
                ],
            ],
        ],
    ],
];

Monolog 文档: SyslogHandler PHP openlog(): openlog

ErrorLogHandler

将日志记录到PHP的error_log()函数中。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'errorlog',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'messageType'    => \Monolog\Handler\ErrorLogHandler::OPERATING_SYSTEM, // Optional:  Says where the error should go.
                    'level'          => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'         => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                    'expandNewlines' => false, // Optional: If set to true, newlines in the message will be expanded to be take multiple log entries
                ],
            ],
        ],
    ],
];

Monolog 文档: ErrorLogHandler

ProcessHandler

将日志记录到由命令指定的任何进程的STDIN中。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'errorlog',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'command' => 'some-command', // Command for the process to start. Absolute paths are recommended, especially if you do not use the $cwd parameter.
                    'level'   => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'  => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                    'cwd'     => __DIR__, // Optional: "Current working directory" (CWD) for the process to be executed in.
                ],
            ],
        ],
    ],
];

Monolog 文档: ProcessHandler

发送警报和电子邮件

NativeMailerHandler

使用PHP的mail()函数发送电子邮件。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'nativeMailer',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'to'             => ['email1@test.com', 'email2@test.com'], // The receiver of the mail. Can be an array or string
                    'subject'        => 'Error Log', // The subject of the mail
                    'from'           => 'sender@test.com', // The sender of the mail
                    'level'          => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'         => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                    'maxColumnWidth' => 80, // Optional: The maximum column width that the message lines will have
                ],
            ],
        ],
    ],
];

Monolog 文档: NativeMailerHandler

SwiftMailerHandler

使用 Swift_Mailer 实例发送电子邮件。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'swiftMailer',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'mailer'  => 'my-service', // The mailer to use.  Must be a valid service name in the container
                    'message' => 'my-message', // An example message for real messages, only the body will be replaced.  Must be a valid service name or callable
                    'level'   => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'  => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档: SwiftMailerHandler

PushoverHandler

通过 Pushover API 发送移动通知。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'pushover',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'token'             => 'sometokenhere', // Pushover api token
                    'users'             => ['email1@test.com', 'email2@test.com'], // Pushover user id or array of ids the message will be sent to
                    'title'             => 'Error Log', // Optional: Title sent to the Pushover API
                    'level'             => \Monolog\Logger::INFO, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'            => false, // Optional:  Whether the messages that are handled can bubble up the stack or not
                    'useSSL'            => false, // Optional:  Whether to connect via SSL. Required when pushing messages to users that are not the pushover.net app owner. OpenSSL is required for this option.
                    'highPriorityLevel' => \Monolog\Logger::WARNING, // Optional: The minimum logging level at which this handler will start sending "high priority" requests to the Pushover API
                    'emergencyLevel'    => \Monolog\Logger::ERROR, // Optional: The minimum logging level at which this handler will start sending "emergency" requests to the Pushover API
                    'retry'             => '22', // Optional: The retry parameter specifies how often (in seconds) the Pushover servers will send the same notification to the user.
                    'expire'            => '300', // Optional: The expire parameter specifies how many seconds your notification will continue to be retried for (every retry seconds).
                ],
            ],
        ],
    ],
];

Monolog 文档: PushoverHandler

FlowdockHandler

将记录日志到 Flowdock 账户。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'flowdock',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'apiToken' => 'sometokenhere', // HipChat API Token
                    'level'    => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'   => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档: FlowdockHandler

SlackWebhookHandler

使用 Slack Webhooks 将记录日志到 Slack 账户。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'slackWebhook',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'webhookUrl'             => 'webhook.slack.com', // Slack Webhook URL
                    'channel'                => 'channel', // Slack channel (encoded ID or name)
                    'userName'               => 'Monolog', // Name of a bot
                    'useAttachment'          => false, // Optional: Whether the message should be added to Slack as attachment (plain text otherwise)
                    'iconEmoji'              => null, // Optional: The emoji name to use (or null)
                    'useShortAttachment'     => true, // Optional: Whether the the context/extra messages added to Slack as attachments are in a short style
                    'includeContextAndExtra' => true, // Optional: Whether the attachment should include context and extra data
                    'level'                  => \Monolog\Logger::INFO, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'                 => false, // Optional: Whether the messages that are handled can bubble up the stack or not
                    'excludeFields'          => ['context.field1', 'extra.field2'], // Optional: Dot separated list of fields to exclude from slack message.
                ],
            ],
        ],
    ],
];

Monolog 文档: SlackWebhookHandler

SlackHandler

使用 Slack API (复杂配置) 将记录日志到 Slack 账户。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'slack',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'token     '             => 'apiToken', // Slack API token
                    'channel'                => 'channel', // Slack channel (encoded ID or name)
                    'userName'               => 'Monolog', // Name of a bot
                    'useAttachment'          => false, // Optional: Whether the message should be added to Slack as attachment (plain text otherwise)
                    'iconEmoji'              => null, // Optional: The emoji name to use (or null)
                    'useShortAttachment'     => true, // Optional: Whether the the context/extra messages added to Slack as attachments are in a short style
                    'includeContextAndExtra' => true, // Optional: Whether the attachment should include context and extra data
                    'level'                  => \Monolog\Logger::INFO, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'                 => false, // Optional: Whether the messages that are handled can bubble up the stack or not
                    'excludeFields'          => ['context.field1', 'extra.field2'], // Optional: Dot separated list of fields to exclude from slack message.
                ],
            ],
        ],
    ],
];

Monolog 文档: SlackHandler

SendGridHandler

通过 SendGrid API 发送电子邮件。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'sendgrid',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'apiUser'                => 'apiUser', // The SendGrid API User
                    'apiKey'                 => 'apiKey', // The SendGrid API Key
                    'from'                   => 'from', // The sender of the email
                    'to'                     => 'to', // string or array of recipients
                    'subject'                => 'subject', // The subject of the mail
                    'level'                  => \Monolog\Logger::INFO, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'                 => false, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档: SendGridHandler

MandrillHandler

使用 Mandrill API 以及 Swift_Message 实例发送电子邮件。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'mandrill',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'apiKey'  => 'my-service', // A valid Mandrill API key
                    'message' => 'my-message', // An example \Swiftmail message for real messages, only the body will be replaced.  Must be a valid service name or callable
                    'level'   => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'  => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档: MandrillHandler

FleepHookHandler

使用 Webhooks 将记录日志到 Fleep 对话。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'fleepHook',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'token'  => 'sometokenhere', // Webhook token
                    'level'  => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档: FleepHookHandler

TelegramBotHandler

将记录日志到 Telegram 机器人账户。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'telegrambot',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'apiKey' => 'api-key', // Api Key
                    'channel' => 'api-key', // Channel
                    'level'    => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'   => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档: TelegramBotHandler

日志特定服务器和网络化日志

SocketHandler

将日志记录到套接字,适用于UNIX和TCP套接字。请参阅示例

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'socket',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'connectionString' => 'unix:///var/log/httpd_app_log.socket', // Socket connection string.  You can use a unix:// prefix to access unix sockets and udp:// to open UDP sockets instead of the default TCP.
                    'timeout'          => 30, // Optional: The connection timeout, in seconds.
                    'writeTimeout'     => 90, // Optional: Set timeout period on a stream.
                    'level'            => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'           => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:SocketHandler

AmqpHandler

将日志记录到兼容AMQP的服务器。需要php-amqp扩展(1.0+)或php-amqplib库。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'amqp',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'exchange'     => 'my-service', // AMQPExchange (php AMQP ext) or PHP AMQP lib channel.  Must be a valid service.
                    'exchangeName' => 'log-name', // Optional: Exchange name, for AMQPChannel (PhpAmqpLib) only
                    'level'        => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'       => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:AmqpHandler

GelfHandler

将日志记录到Graylog2服务器。需要安装graylog2/gelf-php包。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'gelf',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'publisher' => 'my-service', // A Gelf\PublisherInterface object.  Must be a valid service.
                    'level'     => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'    => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:GelfHandler

CubeHandler

将日志记录到Cube服务器。

注意:Cube已停止活跃开发、维护或支持,Square(或其原始作者Mike Bostock)已内部弃用超过一年。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'cube',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'url'    => 'http://test.com:80', // A valid url.  Must consist of three parts : protocol://host:port
                    'level'  => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:CubeHandler

ZendMonitorHandler

将日志记录到Zend Server中的Zend Monitor。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'zend',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'level'  => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:ZendMonitorHandler

NewRelicHandler

将日志记录到NewRelic应用程序。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'newRelic',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'level'           => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'          => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                    'appName'         => 'my-app', // Optional: Application name
                    'explodeArrays'   => 'false', // Optional: Explode Arrays
                    'transactionName' => 'my-transaction', // Optional: Explode Arrays
                ],
            ],
        ],
    ],
];

Monolog 文档:NewRelicHandler

LogglyHandler

将日志记录到Loggly账户。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'loggly',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'token'  => 'sometokenhere', // Webhook token
                    'level'  => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:LogglyHandler

RollbarHandler

将日志记录到Rollbar账户。

注意:RollbarHandler与上游更改脱节。此外,Rollbar库建议使用PsrHandler。请参阅Rollbar 文档了解如何设置。

Monolog 文档:RollbarHandler

SyslogUdpHandler

将日志记录到远程Syslogd服务器。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'syslogUdp',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'host'     => 'somewhere.com', // Host
                    'port'     => 513, //  Optional: Port
                    'facility' => 'Me', // Optional: Facility
                    'level'    => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'   => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                    'ident'    => 'me-too', // Optional: Program name or tag for each log message.
                ],
            ],
        ],
    ],
];

Monolog 文档:SyslogUdpHandler

LogEntriesHandler

将日志记录到LogEntries账户。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'logEntries',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'token'  => 'sometokenhere', // Log token supplied by LogEntries
                    'useSSL' => true, // Optional: Whether or not SSL encryption should be used.
                    'level'  => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:LogEntriesHandler

InsightOpsHandler

将日志记录到InsightOps账户。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'insightops',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'token'  => 'sometokenhere', // Log token supplied by InsightOps
                    'region' => 'region', // Region where InsightOps account is hosted. Could be 'us' or 'eu'.
                    'useSSL' => true, // Optional: Whether or not SSL encryption should be used.
                    'level'  => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:InsightOpsHandler

LogmaticHandler

将日志记录到Logmatic账户。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'logmatic',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'token'  => 'sometokenhere', // Log token supplied by Logmatic.
                    'hostname' => 'region', //  Optional: Host name supplied by Logmatic.
                    'appname' => 'region', //  Optional: Application name supplied by Logmatic.
                    'useSSL' => true, // Optional: Whether or not SSL encryption should be used.
                    'level'  => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:LogmaticHandler

SqsHandler

将日志记录到AWS SQS队列。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'sqs',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'sqsClient' => 'my-service', // SQS Client.  Must be a valid service name in the container.
                    'queueUrl'  => 'url', // URL to SQS Queue
                    'level'  => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:SqsHandler

开发中的日志记录

FirePHPHandler

FirePHP的处理器,在FireBug中提供内联控制台消息。

注意:Firebug 扩展不再开发和维护。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'firePHP',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'level'  => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:FirePHPHandler

ChromePHPHandler

ChromePHP的处理器,在Chrome中提供内联控制台消息。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'chromePHP',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'level'  => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:ChromePHPHandler

BrowserConsoleHandler

不需要浏览器扩展即可将日志发送到浏览器的JavaScript控制台。支持大多数支持console API的浏览器。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'browserConsole',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'level'  => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:BrowserConsoleHandler

PHPConsoleHandler

PHP Console的处理器,在Chrome中提供内联控制台和通知弹出消息。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'phpConsole',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'options' => [], // Optional: See \Monolog\Handler\PHPConsoleHandler::$options for more details
                    'connector' => 'my-service', // Optional:  Instance of \PhpConsole\Connector class. Must be a valid service.
                    'level'  => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:PHPConsoleHandler

### 开发中的日志记录

RedisHandler

将日志记录到Redis服务器。需要php-redis扩展或Predis库。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'redis',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'client'  => 'my-redis-service-name', // The redis instance.  Must be either a [Predis] client OR a Pecl Redis instance
                    'key'     => 'my-service', // The key name to push records to
                    'level'   => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'  => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                    'capSize' => true, // Optional: Number of entries to limit list size to, 0 = unlimited
                ],
            ],
        ],
    ],
];

Monolog 文档:RedisHandler

MongoDBHandler

通过Mongo扩展连接将记录写入MongoDB的处理程序。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'mongo',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'client'     => 'my-mongo-service-name', // MongoDB library or driver instance.
                    'database'   => 'my-db', // Database name
                    'collection' => 'collectionName', // Collection name
                    'level'      => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'     => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                    'capSize'    => true, // Optional: Number of entries to limit list size to, 0 = unlimited
                ],
            ],
        ],
    ],
];

Monolog 文档:MongoDBHandler

CouchDBHandler

将记录记录到CouchDB服务器。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'couchDb',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'host'     => 'localhost',  // Optional: Hostname/Ip address,  Default: 'localhost'
                    'port'     => 5984, // Optional: port,  Default: 5984
                    'dbname'   => 'db', // Optional: Database Name,  Default: 'logger'
                    'username' => 'someuser', // Optional: Username,  Default: null
                    'password' => 'somepass', // Optional: Password,  Default: null
                    'level'    => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'   => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:CouchDBHandler

DoctrineCouchDBHandler

通过Doctrine CouchDB ODM将记录记录到CouchDB服务器。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'doctrineCouchDb',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'client' => 'my-service', //  CouchDBClient service name.  Must be a valid container service
                    'level'  => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:DoctrineCouchDBHandler

ElasticaHandler

将记录记录到Elastic Search服务器。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'elastica',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'client'      => 'my-service', //  Elastica Client object.  Must be a valid container service
                    'index'       => 'monolog', // Optional: Elastic index name
                    'type'        => 'record', // Optional: Elastic document type
                    'ignoreError' => false, // Optional: Suppress Elastica exceptions
                    'level'       => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'      => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:ElasticSearchHandler

DynamoDbHandler

使用AWS SDK将记录记录到DynamoDB表。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'dynamoDb',
                'formatter' => 'formatterName', // Optional: Formatter for the handler.  Default for the handler will be used if not supplied
                'options' => [
                    'client'      => 'my-service', //  DynamoDbClient object.  Must be a valid container service
                    'table'       => 'monolog', // Table name
                    'level'       => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'      => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:DynamoDbHandler

包装器/特殊处理程序

FingersCrossedHandler

一个非常有趣的包装器。它接受一个记录器作为参数,并将所有级别的记录累积到定义的严重性级别超过为止。在这一点上,它将所有记录(包括较低严重性的记录)传递给它包装的处理程序。这意味着在实际错误发生之前,你不会在日志中看到任何内容,但一旦发生,你将获得完整的信息,包括调试和常规记录。这为你提供了所需的所有信息,但只有在你需要的时候才提供。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'fingersCrossed',
                'options' => [
                    'handler'            => 'my-handler', // Required: Registered Handler to wrap
                    'activationStrategy' => 'my-service', // Optional: Strategy which determines when this handler takes action.  Must be either the error level or configured ActivationStrategyInterface service
                    'bufferSize'         => 0,            // Optional: How many entries should be buffered at most, beyond that the oldest items are removed from the buffer.
                    'bubble'             => true,         // Optional: Whether the messages that are handled can bubble up the stack or not
                    'stopBuffering'      => true,         // Optional: Whether the handler should stop buffering after being triggered (default true)
                    'passthruLevel'      => null,         // Optional: Minimum level to always flush to handler on close, even if strategy not triggered
                ],
            ],
        ],
    ],
];

Monolog 文档:FingersCrossedHandler

DeduplicationHandler

如果在发生关键错误时发送通知或电子邮件,则非常有用。它接受一个记录器作为参数,并将所有级别的记录累积到请求结束(或调用flush())为止。在这一点上,它将所有记录传递给它包装的处理程序,但只有当记录在给定时间周期内(默认为60秒)是唯一的。如果记录是重复的,则简单地丢弃它们。此功能的主要用途是在发生关键故障(例如,如果数据库不可达)的情况下,所有请求都会失败,这可能导致发送大量通知。添加此处理程序可以将通知的数量减少到可管理的水平。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'deduplication',
                'options' => [
                    'handler'            => 'my-handler',           // Required: Registered Handler to wrap
                    'deduplicationStore' => '/tmp/somestore',       // Optional: The file/path where the deduplication log should be kept
                    'deduplicationLevel' => \Monolog\Logger::ERROR, // Optional:The minimum logging level for log records to be looked at for deduplication purposes
                    'time'               => 60,                     // Optional: The period (in seconds) during which duplicate entries should be suppressed after a given log is sent through
                    'bubble'             => true,                   // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:DeduplicationHandler

WhatFailureGroupHandler

此处理程序扩展了GroupHandler,忽略每个子处理程序引发的异常。这允许你忽略远程TCP连接可能已死亡的问题,但你不想使整个应用程序崩溃,并可能希望继续将记录记录到其他处理程序。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'whatFailureGroup',
                'options' => [
                    'handlers' => ['my-handler-one'. 'my-handler-two'], // Required: Array of Registered Handlers to wrap
                    'bubble'   => true,                                 // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档: WhatFailureGroupHandler

FallbackGroupHandler

此处理器扩展了GroupHandler,忽略每个子处理器抛出的异常,直到有一个没有抛出异常进行处理。这允许你忽略远程TCP连接可能已断开的问题,但你不想整个应用程序崩溃,可能希望继续尝试将日志记录到其他处理器,直到没有抛出异常。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'fallbackgroup',
                'options' => [
                    'handlers' => ['my-handler-one'. 'my-handler-two'], // Required: Array of Registered Handlers to wrap
                    'bubble'   => true,                                 // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档: FallbackGroupHandler

BufferHandler

此处理器将接收到的所有日志记录缓冲起来,直到调用close(),此时它将一次性在它包装的处理器上调用handleBatch(),将所有日志消息处理完毕。例如,这非常有用,可以一次性发送包含所有记录的邮件,而不是为每个日志记录发送一封邮件。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'buffer',
                'options' => [
                    'handler'         => 'my-handler',           // Required: Registered Handler to wrap
                    'bufferLimit'     => 0,                      // Optional: How many entries should be buffered at most, beyond that the oldest items are removed from the buffer.
                    'level'           => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'          => true,                   // Optional: Whether the messages that are handled can bubble up the stack or not
                    'flushOnOverflow' => false,                  // Optional: If true, the buffer is flushed when the max size has been reached, by default oldest entries are discarded
                ],
            ],
        ],
    ],
];

Monolog 文档: BufferHandler

GroupHandler

此处理器将其他处理器分组。每个接收到的记录都会发送到它配置的所有处理器。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'group',
                'options' => [
                    'handlers' => ['my-handler-one'. 'my-handler-two'], // Required: Array of Registered Handlers to wrap
                    'bubble'   => true,                                 // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档: GroupHandler

FilterHandler

基于一系列级别的简单处理器包装器,用于过滤记录

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'filter',
                'options' => [
                    'handler'         => 'my-handler',               // Required: Registered Handler to wrap
                    'minLevelOrList'  => \Monolog\Logger::DEBUG,     // Optional: An array of levels to accept or a minimum level if maxLevel is provided
                    'maxLevel'        => \Monolog\Logger::EMERGENCY, // Optional: Maximum level to accept, only used if $minLevelOrList is not an array
                    'bubble'          => true,                       // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档: FilterHandler

SamplingHandler

采样事件流在生产环境中非常有用,尤其是在只需要了解正在发生的事情而不关心捕获每个事件的情况。由于是否处理特定事件的决定是随机的,因此生成的采样日志不保证包含应用程序中发生的1/N的事件,但根据大数定律,在大量尝试的情况下,它将趋于接近这个比例。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'sampling',
                'options' => [
                    'handler' => 'my-handler', // Required: Registered Handler to wrap
                    'factor'  => 5,            // Required: Sample factor
                ],
            ],
        ],
    ],
];

Monolog 文档: SamplingHandler

NoopHandler

此处理器通过什么都不做来处理任何东西。它不会停止处理堆栈中的其他部分。这可以用于测试,或在覆盖配置时禁用处理器。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type'    => 'noop',
                'options' => [],
            ],
        ],
    ],
];

Monolog 文档: NoopHandler

NullHandler

它可以处理的任何记录都将被丢弃。这可以用于在现有堆栈上临时覆盖它。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type'    => 'noop',
                'options' => [
                    'level' => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                ],
            ],
        ],
    ],
];

Monolog 文档: NullHandler

PsrHandler

可以将日志记录转发到现有的PSR-3日志记录器

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type'    => 'psr',
                'options' => [
                    'logger' => 'loggerService',        // Required: Logger Service to wrap from the container
                    'level'  => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble' => true,                   // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档: PsrHandler

TestHandler

用于测试,它会记录发送给它的所有内容,并具有访问器来读取信息。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type'    => 'test',
                'options' => [
                    'level'  => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble' => true,                   // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:TestHandler

OverflowHandler

此处理程序将缓冲接收到的所有日志消息,直到达到配置的特定级别的消息数量的阈值。之后,它将所有日志消息传递给包装处理程序。当您只对重要失败感兴趣,而不是对小的、单独的错误事件感兴趣时,适用于批量处理。

<?php

return [
    'monolog' => [
        'handlers' => [
            'myHandlerName' => [
                'type' => 'overflow',
                'options' => [
                    'handlers' => 'my-handler', // Required: Registered Handler to wrap
                    'thresholdMap' => [  // Optional: threshold map
                        'debug' => 2, // Optional: debug threshold.  Default: 0
                        'info' => 2, // Optional: info threshold.  Default: 0
                        'notice' => 2, // Optional: notice threshold.  Default: 0
                        'warning' => 2, // Optional: warning threshold.  Default: 0
                        'error' => 2, // Optional: error threshold.  Default: 0
                        'critical' => 2, // Optional: critical threshold.  Default: 0
                        'alert' => 2, // Optional: alert threshold.  Default: 0
                        'emergency' => 2, // Optional: emergency threshold.  Default: 0
                    ],
                    'level'  => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this handler will be triggered
                    'bubble'   => true, // Optional: Whether the messages that are handled can bubble up the stack or not
                ],
            ],
        ],
    ],
];

Monolog 文档:OverflowHandler

格式化器

LineFomatter

将日志记录格式化为单行字符串。

<?php

return [
    'monolog' => [
        'formatters' => [
            'myFormatterName' => [
                'type' => 'line',
                'options' => [
                    'format'                     => "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n",  // Optional
                    'dateFormat'                 => "c", // Optional : The format of the timestamp: one supported by DateTime::format
                    'allowInlineLineBreaks'      => false, // Optional : Whether to allow inline line breaks in log entries
                    'ignoreEmptyContextAndExtra' => false, // Optional
                ],
            ],
        ],
    ],
];

Monolog 文档:LineFormatter

HtmlFormatter

用于将日志记录格式化为可读的 HTML 表格,主要适用于电子邮件。

<?php

return [
    'monolog' => [
        'formatters' => [
            'myFormatterName' => [
                'type' => 'html',
                'options' => [
                    'dateFormat' => "c", // Optional
                ],
            ],
        ],
    ],
];

Monolog 文档:HtmlFormatter

NormalizerFormatter

将对象/资源规范化为字符串,以便记录可以轻松序列化/编码。

<?php

return [
    'monolog' => [
        'formatters' => [
            'myFormatterName' => [
                'type' => 'normalizer',
                'options' => [
                    'dateFormat' => "c", // Optional
                ],
            ],
        ],
    ],
];

Monolog 文档:NormalizerFormatter

ScalarFormatter

用于将日志记录格式化为标量值的关联数组。

<?php

return [
    'monolog' => [
        'formatters' => [
            'myFormatterName' => [
                'type' => 'scalar',
                'options' => [], // No options available
            ],
        ],
    ],
];

Monolog 文档:ScalarFormatter

JsonFormatter

将日志记录编码为 JSON。

<?php

return [
    'monolog' => [
        'formatters' => [
            'myFormatterName' => [
                'type' => 'json',
                'options' => [
                    'batchMode'     => \Monolog\Formatter\JsonFormatter::BATCH_MODE_JSON, //optional
                    'appendNewline' => true, //optional
                ],
            ],
        ],
    ],
];

Monolog 文档:JsonFormatter

WildfireFormatter

用于将日志记录格式化为 Wildfire/FirePHP 协议,仅适用于 FirePHPHandler。

<?php

return [
    'monolog' => [
        'formatters' => [
            'myFormatterName' => [
                'type' => 'wildfire',
                'options' => [
                    'dateFormat' => "c", // Optional
                ],
            ],
        ],
    ],
];

Monolog 文档:WildfireFormatter

ChromePHPFormatter

用于将日志记录格式化为 ChromePHP 格式,仅适用于 ChromePHPHandler。

<?php

return [
    'monolog' => [
        'formatters' => [
            'myFormatterName' => [
                'type' => 'chromePHP',
                'options' => [], // No options available
            ],
        ],
    ],
];

Monolog 文档:ChromePHPFormatter

GelfMessageFormatter

用于将日志记录格式化为 Gelf 消息实例,仅适用于 GelfHandler。

<?php

return [
    'monolog' => [
        'formatters' => [
            'myFormatterName' => [
                'type' => 'gelf',
                'options' => [
                    'systemName'    => "my-system",  // Optional : the name of the system for the Gelf log message, defaults to the hostname of the machine
                    'extraPrefix'   => "extra_", // Optional : a prefix for 'extra' fields from the Monolog record
                    'contextPrefix' => 'ctxt_', // Optional : a prefix for 'context' fields from the Monolog record
                    'maxLength'     => 32766, // Optional : Length per field
                ],
            ],
        ],
    ],
];

Monolog 文档:GelfMessageFormatter

LogstashFormatter

用于将日志记录格式化为 logstash 事件 JSON,适用于此处列出的任何处理程序。

<?php

return [
    'monolog' => [
        'formatters' => [
            'myFormatterName' => [
                'type' => 'logstash',
                'options' => [
                    'applicationName' => 'app-name', // the application that sends the data, used as the "type" field of logstash
                    'systemName'      => "my-system",  // Optional : the system/machine name, used as the "source" field of logstash, defaults to the hostname of the machine
                    'extraPrefix'     => "extra_", // Optional : prefix for extra keys inside logstash "fields"
                    'contextPrefix'   => 'ctxt_', // Optional : prefix for context keys inside logstash "fields", defaults to ctxt_
                ],
            ],
        ],
    ],
];

Monolog 文档:LogstashFormatter

ElasticaFormatter

用于将日志记录格式化为logstash事件JSON,对输入列表中任何处理器都很有用。这里有详细说明。

<?php

return [
    'monolog' => [
        'formatters' => [
            'ElasticaFormatter' => [
                'type' => 'elastica',
                'options' => [
                    'index'   => 'some-index', // Elastic search index name
                    'type'    => "doc-type",  // Elastic search document type
                ],
            ],
        ],
    ],
];

Monolog 文档:ElasticaFormatter

LogglyFormatter

用于将日志记录格式化为Loggly消息,仅对Loggly处理器有用。

<?php

return [
    'monolog' => [
        'formatters' => [
            'myFormatterName' => [
                'type' => 'loggly',
                'options' => [
                    'batchMode'     => \Monolog\Formatter\JsonFormatter::BATCH_MODE_NEWLINES, //optional
                    'appendNewline' => false, //optional
                ],
            ],
        ],
    ],
];

Monolog 文档:LogglyFormatter

FlowdockFormatter

用于将日志记录格式化为Flowdock消息,仅对Flowdock处理器有用。

<?php

return [
    'monolog' => [
        'formatters' => [
            'myFormatterName' => [
                'type' => 'flowdock',
                'options' => [
                    'source'      => 'Some Source',
                    'sourceEmail' => 'source@email.com'
                ],
            ],
        ],
    ],
];

Monolog 文档:FlowdockFormatter

MongoDBFormatter

将\DateTime实例转换为\MongoDate,并将对象递归转换为数组,仅与MongoDB处理器一起使用。

<?php

return [
    'monolog' => [
        'formatters' => [
            'myFormatterName' => [
                'type' => 'mongodb',
                'options' => [
                    'maxNestingLevel'        => 3, // optional : 0 means infinite nesting, the $record itself is level 1, $record['context'] is 2
                    'exceptionTraceAsString' => true, // optional : set to false to log exception traces as a sub documents instead of strings
                ],
            ],
        ],
    ],
];

Monolog 文档:MongoDBFormatter

LogmaticFormatter

将日志记录格式化为Logmatic消息,仅对Logmatic处理器有用。

<?php

return [
    'monolog' => [
        'formatters' => [
            'myFormatterName' => [
                'type' => 'json',
                'options' => [
                    'batchMode'     => \Monolog\Formatter\LogmaticFormatter::BATCH_MODE_JSON, //optional
                    'appendNewline' => true, //optional
                    'hostname' => 'my-host', //optional 'hostname' parameter for indexing by Logmatic
                    'appName' => 'app name', //optional 'appname' parameter for indexing by Logmatic
                ],
            ],
        ],
    ],
];

Monolog 文档:LogmaticFormatter

处理器

PsrLogMessageProcessor

根据PSR-3规则处理日志记录的消息,将{foo}替换为$context['foo']中的值。

<?php

return [
    'monolog' => [
        'processors' => [
            'myProcessorsName' => [
                'type' => 'psrLogMessage',
                'options' => [], // No options
            ],
        ],
    ],
];

Monolog 文档:PsrLogMessageProcessor

IntrospectionProcessor

添加日志调用来源的行、文件、类和方法。

<?php

return [
    'monolog' => [
        'processors' => [
            'myProcessorsName' => [
                'type' => 'introspection',
                'options' => [
                    'level'                => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this processor will be triggered
                    'skipClassesPartials'  => [], // Optional
                    'skipStackFramesCount' => 0, // Optional
                ],
            ],
        ],
    ],
];

Monolog 文档:IntrospectionProcessor

WebProcessor

将当前请求URI、请求方法和客户端IP地址添加到日志记录中。

<?php

return [
    'monolog' => [
        'processors' => [
            'myProcessorsName' => [
                'type' => 'web',
                'options' => [
                    'serverData'  => 'my-service', // Optional: Array, object w/ ArrayAccess, or valid service name that provides access to the $_SERVER data
                    'extraFields' => [], // Optional: Field names and the related key inside $serverData to be added. If not provided it defaults to: url, ip, http_method, server, referrer
                ],
            ],
        ],
    ],
];

Monolog 文档:WebProcessor

MemoryUsageProcessor

将当前内存使用情况添加到日志记录中。

<?php

return [
    'monolog' => [
        'processors' => [
            'myProcessorsName' => [
                'type' => 'memoryUsage',
                'options' => [], // No options
            ],
        ],
    ],
];

Monolog 文档:MemoryUsageProcessor

MemoryPeakUsageProcessor

将峰值内存使用情况添加到日志记录中。

<?php

return [
    'monolog' => [
        'processors' => [
            'myProcessorsName' => [
                'type' => 'memoryPeak',
                'options' => [], // No options
            ],
        ],
    ],
];

Monolog 文档:MemoryPeakUsageProcessor

ProcessIdProcessor

将进程ID添加到日志记录中。

<?php

return [
    'monolog' => [
        'processors' => [
            'myProcessorsName' => [
                'type' => 'processId',
                'options' => [], // No options
            ],
        ],
    ],
];

Monolog 文档:ProcessIdProcessor

UidProcessor

将唯一标识符添加到日志记录中。

<?php

return [
    'monolog' => [
        'processors' => [
            'myProcessorsName' => [
                'type' => 'uid',
                'options' => [
                    'length'  => 7, // Optional: The uid length. Must be an integer between 1 and 32
                ],
            ],
        ],
    ],
];

Monolog 文档:UidProcessor

GitProcessor

将当前的git分支和提交添加到日志记录中。

注意:只有当git可执行文件在您的当前工作路径中时才有效。

<?php

return [
    'monolog' => [
        'processors' => [
            'myProcessorsName' => [
                'type' => 'git',
                'options' => [
                    'level'  => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this processor will be triggered
                ],
            ],
        ],
    ],
];

Monolog 文档:GitProcessor

MercurialProcessor

将当前的hg分支和提交添加到日志记录中。

注意:只有当hg可执行文件在您的当前工作路径中时才有效。

<?php

return [
    'monolog' => [
        'processors' => [
            'myProcessorsName' => [
                'type' => 'mercurial',
                'options' => [
                    'level'  => \Monolog\Logger::DEBUG, // Optional: The minimum logging level at which this processor will be triggered
                ],
            ],
        ],
    ],
];

Monolog 文档:MercurialProcessor

TagProcessor

将预定义的标签数组添加到日志记录中。

<?php

return [
    'monolog' => [
        'processors' => [
            'myProcessorsName' => [
                'type' => 'tags',
                'options' => [
                    'tags'  => [], // Optional: Array of tags to add to records
                ],
            ],
        ],
    ],
];

Monolog 文档:TagProcessor

HostnameProcessor

将当前的主机名添加到日志记录中。

<?php

return [
    'monolog' => [
        'processors' => [
            'myProcessorsName' => [
                'type' => 'hostname',
                'options' => [], // No options
            ],
        ],
    ],
];

Monolog 文档:HostnameProcessor

升级

从版本2升级到版本3

版本3将Monolog包从版本1升级到版本2。这带来了许多破坏性变化。请参阅UPGRADE.md了解上游的变化列表。

此包现在还要求PHP 7.2。

从版本1升级到版本2

当从版本1升级到版本2时,不需要进行任何更改。请注意,直接使用ChannelChanger不再推荐。应使用命名服务。请参阅上文获取更多信息。

更改
  • 自动将“default”通道条目和处理程序添加到配置中。此默认通道要求您指定通道的配置处理程序,或者必须有配置的'default'通道才能使用。大多数版本1用户应不会对此更改有任何问题,并且工厂应该仍然正常工作。