blazon / psr11-monolog
Monolog Factories for PSR-11
Requires
- php: ^8.0
- monolog/monolog: ^2.3
- psr/container: ^1.0
Requires (Dev)
- aws/aws-sdk-php: ^3.185
- doctrine/couchdb: 1.0.0-beta4
- graylog2/gelf-php: ^1.7
- mongodb/mongodb: ^1.9
- php-amqplib/php-amqplib: ^3.0
- php-console/php-console: ^3.1
- phpmd/phpmd: ^2.10
- phpstan/phpstan: ^0.12
- phpunit/phpunit: ^9.5
- predis/predis: ^1.1
- ruflin/elastica: ^7.1
- squizlabs/php_codesniffer: ^3.6
- swiftmailer/swiftmailer: ^6.2
- symfony/dependency-injection: ^5.3
- vimeo/psalm: ^4.8
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
PSR-11 Monolog
Monolog Factories for PSR-11
Table of Contents
- Installation
- Usage
- Containers
- Frameworks
- Configuration
- Minimal Configuration
- Full Configuration
- Channels
- Handlers
- Formatters
- LineFomatter
- HtmlFormatter
- NormalizerFormatter
- ScalarFormatter
- JsonFormatter
- WildfireFormatter
- ChromePHPFormatter
- GelfMessageFormatter
- LogstashFormatter
- ElasticaFormatter
- LogglyFormatter:
- FlowdockFormatter (deprecated)
- MongoDBFormatter
- LogmaticFormatter
- FluentdFormatter
- GoogleCloudLoggingFormatter
- SyslogFormatter
- ElasticsearchFormatter
- RedactingFormatter
- Processors
- Upgrades
Installation
composer require blazon/psr11-monolog
Requires PHP 8.4 or later and Monolog 3.12 or later. Upgrading from version 5? See Upgrading from version 5 to 6.
Usage
<?php
# Get the Channel Changer
$channel = $container->get('my-channel');
# Write to log
$channel->debug('Hi There');
Additional info can be found in the documentation
Containers
Any PSR-11 container wil work. In order to do that you will need to add configuration
and register a new service that points to Blazon\PSR11MonoLog\MonologFactory
Below are some specific container examples to get you started
Pimple
// Create Container
$container = new \Xtreamwayz\Pimple\Container([
// Logger using the default keys.
'logger' => new \Blazon\PSR11MonoLog\MonologFactory(),
// Another logger using a different channel configuration
'other' => function($c) {
return \Blazon\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');
Laminas Service Manager
<?php
// Create the container and define the services you'd like to use
$container = new \Laminas\ServiceManager\ServiceManager([
'factories' => [
// Logger using the default keys.
'logger' => \Blazon\PSR11MonoLog\MonologFactory::class,
// Another logger using a different channel configuration
'channelTwo' => [\Blazon\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');
Frameworks
Any framework that use a PSR-11 should work fine. Below are some specific framework examples to get you started
Mezzio
You'll need to add configuration and register the services you'd like to use. There are number of ways to do that
but the recommended way is to create a new config file config/autoload/monolog.global.php
Configuration
config/autoload/monolog.global.php
<?php
return [
'dependencies' => [
'factories' => [
// Logger using the default keys.
'logger' => \Blazon\PSR11MonoLog\MonologFactory::class,
// Another logger using a different channel configuration
'channelTwo' => [\Blazon\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',
],
],
],
],
];
Laminas
You'll need to add configuration and register the services you'd like to use. There are number of ways to do that
but the recommended way is to create a new config file config/autoload/monolog.global.php
Configuration
config/autoload/monolog.global.php
<?php
return [
'service_manager' => [
'factories' => [
// Logger using the default keys.
'logger' => \Blazon\PSR11MonoLog\MonologFactory::class,
// Another logger using a different channel configuration
'channelTwo' => [\Blazon\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',
],
],
],
],
];
Module Config
If you're not using the Laminas Component Installer you will also need to register the Module.
config/modules.config.php (Laminas skeleton)
<?php
return [
// ... Previously registered modules here
'Blazon\\PSR11MonoLog',
];
Configuration
Monolog uses four types of services that will each need to be configured for your application.
In addition you will need to create a named service that maps to the \Blazon\PSR11MonoLog\MonologFactory
based on the container you are using.
Named Services : These are services names wired up to a factory. The configuration will differ based on the type of container / framework in use.
Channels : Channels are a great way to identify to which part of the application a record is related. This is useful in big applications and is leveraged here.
Picture two loggers sharing a handler that writes to a single log file. Channels allow you to identify the logger that issued every record. You can easily grep through the log files filtering this or that channel.
Handlers : These services do all the heavy lifting and log your message to the wired up system. There are many different handlers available to you, but he one you will most likely want to use for basic file logging is the StreamHandler. Tip: You can use the same handler for multiple channels.
Formatters : (Optional) Formatters are in charge of formatting the message for the handler. Generally you can use the defualt formatter for the handler you are using, in some circumstances you may however want to change the formatting of the message. Configuring a formatter will let you customize the message being sent to the log.
Processors : (Optional) Processors can be used to add data, change the message, filter, you name it. Monolog provides some built-in processors that can be used in your project. Look at the Processors section for the list.
Minimal Configuration
A minimal configuration would consist of at least one default handler and one named service. Please note that if you don't specify a default handler a NullHandler will be used when you wire up the default logger.
Minimal Example (using Mezzio for the example):
<?php
return [
'dependencies' => [
'factories' => [
// Logger using the default keys.
'logger' => \Blazon\PSR11MonoLog\MonologFactory::class,
]
],
'monolog' => [
'handlers' => [
'default' => [
'type' => 'stream',
'options' => [
'stream' => '/var/log/some-log-file.txt',
],
],
],
],
];
Full Configuration
Full Example
<?php
return [
'dependencies' => [
'factories' => [
// Logger using the default keys.
'logger' => \Blazon\PSR11MonoLog\MonologFactory::class,
// Another logger using a different channel configuration
'channelTwo' => [\Blazon\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' => ['default', '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'],
],
],
],
];
Channels
<?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',
],
],
],
],
];
Handlers
Every option is validated before the handler is created, and an invalid value throws a
Blazon\PSR11MonoLog\Exception\InvalidConfigException (or MissingConfigException for a missing required
option) naming the option. Levels must be \Monolog\Level enum cases, such as \Monolog\Level::Error.
Optional options are shown below with their default values, which match Monolog's own defaults.
Log to files and syslog
StreamHandler
Logs records into any PHP stream, use this for log files.
<?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\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
'filePermission' => null, // Optional: Unix file permissions to set on the log file, e.g. 0644. null leaves them to the umask
'useLocking' => false, // Optional: Try to lock log file before doing any writes
'fileOpenMode' => 'a', // Optional: The fopen() mode used to open the stream
],
],
],
],
];
Monolog Docs: StreamHandler
RotatingFileHandler
Logs records to a file and creates one logfile per day. It will also delete files older than $maxFiles. You should use logrotate for high profile setups though, this is just meant as a quick and dirty solution.
<?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\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
'filePermission' => null, // Optional: Unix file permissions to set on the log file, e.g. 0644. null leaves them to the umask
'useLocking' => false, // Optional: Try to lock log file before doing any writes
'dateFormat' => \Monolog\Handler\RotatingFileHandler::FILE_PER_DAY, // Optional: One of the RotatingFileHandler::FILE_PER_HOUR, FILE_PER_DAY, FILE_PER_MONTH or FILE_PER_YEAR constants
'filenameFormat' => '{filename}-{date}', // Optional: Rotated file name format. Must contain {date} and may contain {filename}
'timezone' => null, // Optional: A \DateTimeZone used to compute the rotation date. null uses the default timezone
],
],
],
],
];
Monolog Docs: RotatingFileHandler
SyslogHandler
Logs records to the 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: A LOG_* constant, or a facility name such as 'local0'
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'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
],
],
],
],
];
Monolog Docs: SyslogHandler PHP openlog(): openlog
ErrorLogHandler
Logs records to PHP's error_log() function.
<?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: ErrorLogHandler::OPERATING_SYSTEM or ErrorLogHandler::SAPI
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'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 Docs: ErrorLogHandler
ProcessHandler
Logs records to the STDIN of any process, specified by a command.
<?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', // Required: Command for the process to start. Absolute paths are recommended, especially if you do not use the $cwd parameter
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
'cwd' => null, // Optional: "Current working directory" (CWD) for the process to be executed in
'timeout' => 1.0, // Optional: Seconds to wait for the process to accept the log record
],
],
],
],
];
Monolog Docs: ProcessHandler
FrankenPhpHandler
Logs records to the FrankenPHP server log through frankenphp_log(), alongside
FrankenPHP's own logs. Only works when running under FrankenPHP.
<?php
return [
'monolog' => [
'handlers' => [
'myHandlerName' => [
'type' => 'frankenPhp',
'formatter' => 'formatterName', // Optional: Formatter for the handler. Default for the handler will be used if not supplied
'options' => [
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
],
],
],
],
];
Monolog Docs: FrankenPhpHandler
Send alerts and emails
NativeMailerHandler
Sends emails using PHP's mail() function.
<?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'], // Required: The receiver of the mail. Can be an array or string
'subject' => 'Error Log', // Required: The subject of the mail
'from' => 'sender@test.com', // Required: The sender of the mail
'level' => \Monolog\Level::Error, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
'maxColumnWidth' => 70, // Optional: The maximum column width that the message lines will have
],
],
],
],
];
Monolog Docs: NativeMailerHandler
SymfonyMailerHandler
Sends emails using the Symfony Mailer component. The email service
is used as a template for each email, with the subject and body replaced by the log records. It can also be a
Closure service, called with the formatted content and the records, that returns the Email to send.
<?php
return [
'monolog' => [
'handlers' => [
'myHandlerName' => [
'type' => 'symfonyMailer',
'formatter' => 'formatterName', // Optional: Formatter for the handler. Default for the handler will be used if not supplied
'options' => [
'mailer' => 'my-mailer-service', // Required: \Symfony\Component\Mailer\MailerInterface or \Symfony\Component\Mailer\Transport\TransportInterface object. Must be a valid container service
'email' => 'my-email-service', // Required: \Symfony\Component\Mime\Email template, or a Closure(string $content, LogRecord[] $records): Email. Must be a valid container service
'level' => \Monolog\Level::Error, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
],
],
],
],
];
Monolog Docs: SymfonyMailerHandler
PushoverHandler
Sends mobile notifications via the 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', // Required: Pushover api token
'users' => ['email1@test.com', 'email2@test.com'], // Required: Pushover user id or array of ids the message will be sent to
'title' => null, // Optional: Title sent to the Pushover API
'level' => \Monolog\Level::Critical, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
'useSSL' => true, // 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\Level::Critical, // Optional: The minimum logging level at which this handler will start sending "high priority" requests to the Pushover API
'emergencyLevel' => \Monolog\Level::Emergency, // Optional: The minimum logging level at which this handler will start sending "emergency" requests to the Pushover API
'retry' => 30, // Optional: The retry parameter specifies how often (in seconds) the Pushover servers will send the same notification to the user
'expire' => 25200, // Optional: The expire parameter specifies how many seconds your notification will continue to be retried for (every retry seconds)
'persistent' => false, // Optional: Whether to keep the socket connection open between requests
'timeout' => 0.0, // Optional: Socket timeout, in seconds. 0 means no timeout
'writingTimeout' => 10.0, // Optional: Seconds to wait for a write to complete before giving up
'connectionTimeout' => null, // Optional: Seconds to wait when connecting. null uses default_socket_timeout
'chunkSize' => null, // Optional: Number of bytes to write per fwrite() call. null uses the default
],
],
],
],
];
Monolog Docs: PushoverHandler
FlowdockHandler
Deprecated: Monolog deprecated the FlowdockHandler in 3.3.0 as Flowdock has shut down. This factory will be removed when this library adds Monolog 4 support.
Logs records to a Flowdock account.
<?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', // Required: Flowdock API token
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
'persistent' => false, // Optional: Whether to keep the socket connection open between requests
'timeout' => 0.0, // Optional: Socket timeout, in seconds. 0 means no timeout
'writingTimeout' => 10.0, // Optional: Seconds to wait for a write to complete before giving up
'connectionTimeout' => null, // Optional: Seconds to wait when connecting. null uses default_socket_timeout
'chunkSize' => null, // Optional: Number of bytes to write per fwrite() call. null uses the default
],
],
],
],
];
Monolog Docs: FlowdockHandler
SlackWebhookHandler
Logs records to a Slack account using Slack Webhooks.
<?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', // Required: Slack Webhook URL
'channel' => null, // Optional: Slack channel (encoded ID or name)
'userName' => null, // Optional: Name of a bot
'useAttachment' => true, // 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' => false, // Optional: Whether the the context/extra messages added to Slack as attachments are in a short style
'includeContextAndExtra' => false, // Optional: Whether the attachment should include context and extra data
'level' => \Monolog\Level::Critical, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
'excludeFields' => [], // Optional: Dot separated list of fields to exclude from slack message
],
],
],
],
];
Monolog Docs: SlackWebhookHandler
SlackHandler
Logs records to a SlackHandler account using the Slack API (complex setup).
<?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' => 'my-slack-api-token', // Required: Slack API token
'channel' => 'channel', // Required: Slack channel (encoded ID or name)
'userName' => null, // Optional: Name of a bot
'useAttachment' => true, // Optional: Whether the message should be added to Slack as attachment (plain text otherwise)
'iconEmoji' => null, // Optional: The emoji name to use (or null)
'level' => \Monolog\Level::Critical, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
'useShortAttachment' => false, // Optional: Whether the the context/extra messages added to Slack as attachments are in a short style
'includeContextAndExtra' => false, // Optional: Whether the attachment should include context and extra data
'excludeFields' => [], // Optional: Dot separated list of fields to exclude from slack message
'persistent' => false, // Optional: Whether to keep the socket connection open between requests
'timeout' => 0.0, // Optional: Socket timeout, in seconds. 0 means no timeout
'writingTimeout' => 10.0, // Optional: Seconds to wait for a write to complete before giving up
'connectionTimeout' => null, // Optional: Seconds to wait when connecting. null uses default_socket_timeout
'chunkSize' => null, // Optional: Number of bytes to write per fwrite() call. null uses the default
],
],
],
],
];
Monolog Docs: SlackHandler
SendGridHandler
Sends emails via the 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' => null, // Optional: The SendGrid API User. Not used by SendGrid API v3
'apiKey' => 'apiKey', // Required: The SendGrid API Key
'from' => 'from', // Required: The sender of the email
'to' => 'to', // Required: string or array of recipients
'subject' => 'subject', // Required: The subject of the mail
'level' => \Monolog\Level::Error, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
'apiHost' => 'api.sendgrid.com', // Optional: SendGrid API host
],
],
],
],
];
Monolog Docs: SendGridHandler
FleepHookHandler
Logs records to a Fleep conversation using Webhooks.
<?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', // Required: Webhook token
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
'persistent' => false, // Optional: Whether to keep the socket connection open between requests
'timeout' => 0.0, // Optional: Socket timeout, in seconds. 0 means no timeout
'writingTimeout' => 10.0, // Optional: Seconds to wait for a write to complete before giving up
'connectionTimeout' => null, // Optional: Seconds to wait when connecting. null uses default_socket_timeout
'chunkSize' => null, // Optional: Number of bytes to write per fwrite() call. null uses the default
],
],
],
],
];
Monolog Docs: FleepHookHandler
TelegramBotHandler
Logs records to a Telegram bot account.
<?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', // Required: Api Key
'channel' => 'api-key', // Required: Channel
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
'parseMode' => null, // Optional: Telegram parse mode: 'HTML', 'MarkdownV2' or 'Markdown'
'disableWebPagePreview' => null, // Optional: Disable link previews for links in the message
'disableNotification' => null, // Optional: Send the message silently
'splitLongMessages' => false, // Optional: Split messages longer than 4096 characters into several messages
'delayBetweenMessages' => false, // Optional: Wait 1 second between messages to avoid rate limits
'topic' => null, // Optional: Telegram forum topic id
],
],
],
],
];
Monolog Docs: TelegramBotHandler
Log specific servers and networked logging
SocketHandler
Logs records to sockets, use this for UNIX and TCP sockets. See an example.
<?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' => 'value', // Required: Socket connection string. You can use a unix:// prefix to access unix sockets and udp:// to open UDP sockets instead of the default TCP
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
'persistent' => false, // Optional: Whether to keep the socket connection open between requests
'timeout' => 0.0, // Optional: Socket timeout, in seconds. 0 means no timeout
'writingTimeout' => 10.0, // Optional: Seconds to wait for a write to complete before giving up
'connectionTimeout' => null, // Optional: Seconds to wait when connecting. null uses default_socket_timeout
'chunkSize' => null, // Optional: Number of bytes to write per fwrite() call. null uses the default
],
],
],
],
];
Monolog Docs: SocketHandler
AmqpHandler
Logs records to an AMQP compatible server. Requires the php-amqp extension (1.0+) or the php-amqplib library.
<?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', // Required: AMQPExchange (amqp extension) or PhpAmqpLib AMQPChannel service name
'exchangeName' => null, // Optional: Exchange name, for AMQPChannel (PhpAmqpLib) only
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
],
],
],
],
];
Monolog Docs: AmqpHandler
GelfHandler
Logs records to a Graylog2 server. Requires package 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', // Required: A Gelf\PublisherInterface object. Must be a valid service
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
],
],
],
],
];
Monolog Docs: GelfHandler
CubeHandler
Deprecated: Monolog deprecated the CubeHandler in 3.2.0 as Cube appears abandoned. This factory will be removed when this library adds Monolog 4 support.
Logs records to a Cube server.
Note: Cube is not under active development, maintenance or support by Square (or by its original author Mike Bostock). It has been deprecated internally for over a year.
<?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' => 'value', // Required: A valid url. Must consist of three parts : protocol://host:port
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
],
],
],
],
];
Monolog Docs: CubeHandler
ZendMonitorHandler
Logs records to the Zend Monitor present in Zend Server.
<?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\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
],
],
],
],
];
Monolog Docs: ZendMonitorHandler
NewRelicHandler
Logs records to a NewRelic application.
<?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\Level::Error, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
'appName' => null, // Optional: Application name
'explodeArrays' => false, // Optional: Whether to explode context and extra arrays for display on the New Relic website
'transactionName' => null, // Optional: Name of the current transaction
],
],
],
],
];
Monolog Docs: NewRelicHandler
LogglyHandler
Logs records to a Loggly account.
<?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', // Required: Loggly customer token
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
],
],
],
],
];
Monolog Docs: LogglyHandler
RollbarHandler
Logs records to a Rollbar account. Requires the
rollbar/rollbar library. The RollbarLogger service is created with your
Rollbar configuration, e.g. new \Rollbar\RollbarLogger(['access_token' => '...', 'environment' => 'production']).
<?php
return [
'monolog' => [
'handlers' => [
'myHandlerName' => [
'type' => 'rollbar',
'formatter' => 'formatterName', // Optional: Formatter for the handler. Default for the handler will be used if not supplied
'options' => [
'rollbarLogger' => 'my-service', // Required: \Rollbar\RollbarLogger object. Must be a valid container service
'level' => \Monolog\Level::Error, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
],
],
],
],
];
Monolog Docs: RollbarHandler
SyslogUdpHandler
Logs records to a remote Syslogd server.
<?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', // Required: Host
'port' => 514, // Optional: Port
'facility' => LOG_USER, // Optional: A LOG_* constant, or a facility name such as 'local0'
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
'ident' => 'php', // Optional: Program name or tag for each log message
'rfc' => \Monolog\Handler\SyslogUdpHandler::RFC5424, // Optional: The RFC to format the message for: SyslogUdpHandler::RFC3164, RFC5424 or RFC5424e
'maxLength' => null, // Optional: Maximum datagram length in bytes. null uses Monolog's default
],
],
],
],
];
Monolog Docs: SyslogUdpHandler
LogEntriesHandler
Logs records to a LogEntries account.
<?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', // Required: Log token supplied by LogEntries
'useSSL' => true, // Optional: Whether or not SSL encryption should be used
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
'host' => 'data.logentries.com', // Optional: LogEntries host
'persistent' => false, // Optional: Whether to keep the socket connection open between requests
'timeout' => 0.0, // Optional: Socket timeout, in seconds. 0 means no timeout
'writingTimeout' => 10.0, // Optional: Seconds to wait for a write to complete before giving up
'connectionTimeout' => null, // Optional: Seconds to wait when connecting. null uses default_socket_timeout
'chunkSize' => null, // Optional: Number of bytes to write per fwrite() call. null uses the default
],
],
],
],
];
Monolog Docs: LogEntriesHandler
InsightOpsHandler
Logs records to an InsightOps account.
<?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', // Required: Log token supplied by InsightOps
'region' => 'us', // Optional: Region where InsightOps account is hosted. Could be 'us' or 'eu'
'useSSL' => true, // Optional: Whether or not SSL encryption should be used
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
'persistent' => false, // Optional: Whether to keep the socket connection open between requests
'timeout' => 0.0, // Optional: Socket timeout, in seconds. 0 means no timeout
'writingTimeout' => 10.0, // Optional: Seconds to wait for a write to complete before giving up
'connectionTimeout' => null, // Optional: Seconds to wait when connecting. null uses default_socket_timeout
'chunkSize' => null, // Optional: Number of bytes to write per fwrite() call. null uses the default
],
],
],
],
];
Monolog Docs: InsightOpsHandler
LogmaticHandler
Logs records to a Logmatic account.
<?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', // Required: Log token supplied by Logmatic
'hostname' => '', // Optional: Host name supplied by Logmatic
'appname' => '', // Optional: Application name supplied by Logmatic
'useSSL' => true, // Optional: Whether or not SSL encryption should be used
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
'persistent' => false, // Optional: Whether to keep the socket connection open between requests
'timeout' => 0.0, // Optional: Socket timeout, in seconds. 0 means no timeout
'writingTimeout' => 10.0, // Optional: Seconds to wait for a write to complete before giving up
'connectionTimeout' => null, // Optional: Seconds to wait when connecting. null uses default_socket_timeout
'chunkSize' => null, // Optional: Number of bytes to write per fwrite() call. null uses the default
],
],
],
],
];
Monolog Docs: LogmaticHandler
SqsHandler
Logs records to an AWS SQS queue.
<?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', // Required: SQS Client. Must be a valid service name in the container
'queueUrl' => 'url', // Required: URL to SQS Queue
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
],
],
],
],
];
Monolog Docs: SqsHandler
Logging in development
FirePHPHandler
Handler for FirePHP, providing inline console messages within FireBug.
Note: The Firebug extension isn't being developed or maintained any longer.
<?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\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
],
],
],
],
];
Monolog Docs: FirePHPHandler
ChromePHPHandler
Handler for ChromePHP, providing inline console messages within 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\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
],
],
],
],
];
Monolog Docs: ChromePHPHandler
BrowserConsoleHandler
Handler to send logs to browser's Javascript console with no browser extension required. Most browsers supporting console API are supported.
<?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\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
],
],
],
],
];
Monolog Docs: BrowserConsoleHandler
Log to databases
RedisHandler
Logs records to a Redis server. Requires the php-redis extension or the Predis library.
<?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-service', // Required: Predis\Client or \Redis (phpredis) service name
'key' => 'my-service', // Required: The key name to push records to
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
'capSize' => 0, // Optional: Number of entries to limit list size to, 0 = unlimited
],
],
],
],
];
Monolog Docs: RedisHandler
RedisPubSubHandler
Publishes records to a Redis channel with PUBLISH, for subscribers to receive as they are
logged. Requires the php-redis extension or the
Predis library.
<?php
return [
'monolog' => [
'handlers' => [
'myHandlerName' => [
'type' => 'redisPubSub',
'formatter' => 'formatterName', // Optional: Formatter for the handler. Default for the handler will be used if not supplied
'options' => [
'client' => 'my-service', // Required: Predis\Client or \Redis (phpredis) service name
'key' => 'my-channel', // Required: The channel to publish records to
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
],
],
],
],
];
Monolog Docs: RedisPubSubHandler
MongoDBHandler
Handler to write records in MongoDB via a Mongo extension connection.
<?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-service', // Required: MongoDB\Client or MongoDB\Driver\Manager service name
'database' => 'my-db', // Required: Database name
'collection' => 'collectionName', // Required: Collection name
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
],
],
],
],
];
Monolog Docs: MongoDBHandler
CouchDBHandler
Logs records to a CouchDB server.
<?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
'port' => 5984, // Optional: port
'dbname' => 'logger', // Optional: Database Name
'username' => null, // Optional: Username
'password' => null, // Optional: Password
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
],
],
],
],
];
Monolog Docs: CouchDBHandler
ElasticaHandler
Logs records to an Elastic Search server.
<?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', // Required: Elastica Client object. Must be a valid container service
'index' => 'monolog', // Optional: Elastic index name
'type' => 'record', // Optional: Elastic document type. Unused since Elasticsearch 7
'ignoreError' => false, // Optional: Suppress Elastica exceptions
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
],
],
],
],
];
Monolog Docs: ElasticSearchHandler
ElasticsearchHandler
Logs records to an Elasticsearch server using the official elasticsearch-php client, version 8 or later. Only works with the ElasticsearchFormatter, which is the default.
<?php
return [
'monolog' => [
'handlers' => [
'myHandlerName' => [
'type' => 'elasticsearch',
'formatter' => 'formatterName', // Optional: Must be an ElasticsearchFormatter. Default for the handler will be used if not supplied
'options' => [
'client' => 'my-service', // Required: \Elastic\Elasticsearch\Client object. Must be a valid container service
'index' => 'monolog', // Optional: Elasticsearch index name
'ignoreError' => false, // Optional: Suppress Elasticsearch exceptions
'opType' => 'index', // Optional: Elasticsearch op_type, 'index' or 'create'. Data streams require 'create'
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
],
],
],
],
];
Monolog Docs: ElasticsearchHandler
DynamoDbHandler
Logs records to a DynamoDB table with the AWS SDK.
<?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', // Required: DynamoDbClient object. Must be a valid container service
'table' => 'monolog', // Required: Table name
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
],
],
],
],
];
Monolog Docs: DynamoDbHandler
Wrappers / Special Handlers
FingersCrossedHandler
A very interesting wrapper. It takes a logger as parameter and will accumulate log records of all levels until a record exceeds the defined severity level. At which point it delivers all records, including those of lower severity, to the handler it wraps. This means that until an error actually happens you will not see anything in your logs, but when it happens you will have the full information, including debug and info records. This provides you with all the information you need, but only when you need it.
<?php
return [
'monolog' => [
'handlers' => [
'myHandlerName' => [
'type' => 'fingersCrossed',
'options' => [
'handler' => 'my-handler', // Required: Registered Handler to wrap
'activationStrategy' => null, // Optional: A \Monolog\Level to activate at, or the name of an 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
'passthruLevel' => null, // Optional: Minimum level to always flush to handler on close, even if strategy not triggered
],
],
],
],
];
Monolog Docs: FingersCrossedHandler
DeduplicationHandler
Useful if you are sending notifications or emails when critical errors occur. It takes a logger as parameter and will accumulate log records of all levels until the end of the request (or flush() is called). At that point it delivers all records to the handler it wraps, but only if the records are unique over a given time period (60 seconds by default). If the records are duplicates they are simply discarded. The main use of this is in case of critical failure like if your database is unreachable for example all your requests will fail and that can result in a lot of notifications being sent. Adding this handler reduces the amount of notifications to a manageable level.
<?php
return [
'monolog' => [
'handlers' => [
'myHandlerName' => [
'type' => 'deduplication',
'options' => [
'handler' => 'my-handler', // Required: Registered Handler to wrap
'deduplicationStore' => null, // Optional: The file/path where the deduplication log should be kept
'deduplicationLevel' => \Monolog\Level::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 Docs: DeduplicationHandler
WhatFailureGroupHandler
This handler extends the GroupHandler ignoring exceptions raised by each child handler. This allows you to ignore issues where a remote tcp connection may have died but you do not want your entire application to crash and may wish to continue to log to other handlers.
<?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 Docs: WhatFailureGroupHandler
FallbackGroupHandler
This handler extends the GroupHandler ignoring exceptions raised by each child handler, until one has handled without throwing. This allows you to ignore issues where a remote tcp connection may have died but you do not want your entire application to crash and may wish to continue to attempt log to other handlers, until one does not throw.
<?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 Docs: FallbackGroupHandler
BufferHandler
This handler will buffer all the log records it receives until close() is called at which point it will call handleBatch() on the handler it wraps with all the log messages at once. This is very useful to send an email with all records at once for example instead of having one mail for every log record.
<?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\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'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 Docs: BufferHandler
GroupHandler
This handler groups other handlers. Every record received is sent to all the handlers it is configured with.
<?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 Docs: GroupHandler
FilterHandler
Simple handler wrapper that filters records based on a list of levels
<?php
return [
'monolog' => [
'handlers' => [
'myHandlerName' => [
'type' => 'filter',
'options' => [
'handler' => 'my-handler', // Required: Registered Handler to wrap
'minLevelOrList' => \Monolog\Level::Debug, // Optional: A minimum \Monolog\Level, or an array of the \Monolog\Level values to accept
'maxLevel' => \Monolog\Level::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 Docs: FilterHandler
SamplingHandler
A sampled event stream can be useful for logging high frequency events in a production environment where you only need an idea of what is happening and are not concerned with capturing every occurrence. Since the decision to handle or not handle a particular event is determined randomly, the resulting sampled log is not guaranteed to contain 1/N of the events that occurred in the application, but based on the Law of large numbers, it will tend to be close to this ratio with a large number of attempts.
<?php
return [
'monolog' => [
'handlers' => [
'myHandlerName' => [
'type' => 'sampling',
'options' => [
'handler' => 'my-handler', // Required: Registered Handler to wrap
'factor' => 5, // Required: Sample factor. Must be 1 or more
],
],
],
],
];
Monolog Docs: SamplingHandler
NoopHandler
This handler handles anything by doing nothing. It does not stop processing the rest of the stack. This can be used for testing, or to disable a handler when overriding a configuration.
<?php
return [
'monolog' => [
'handlers' => [
'myHandlerName' => [
'type' => 'noop',
'options' => [],
],
],
],
];
Monolog Docs: NoopHandler
NullHandler
Any record it can handle will be thrown away. This can be used to put on top of an existing stack to override it temporarily.
<?php
return [
'monolog' => [
'handlers' => [
'myHandlerName' => [
'type' => 'noop',
'options' => [
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
],
],
],
],
];
Monolog Docs: NullHandler
PsrHandler
Can be used to forward log records to an existing PSR-3 logger
<?php
return [
'monolog' => [
'handlers' => [
'myHandlerName' => [
'type' => 'psr',
'options' => [
'logger' => 'loggerService', // Required: Logger Service to wrap from the container
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
'includeExtra' => false, // Optional: Whether to include the record's extra data in the context sent to the wrapped logger
],
],
],
],
];
Monolog Docs: PsrHandler
TestHandler
Used for testing, it records everything that is sent to it and has accessors to read out the information.
<?php
return [
'monolog' => [
'handlers' => [
'myHandlerName' => [
'type' => 'test',
'options' => [
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
],
],
],
],
];
Monolog Docs: TestHandler
OverflowHandler
This handler will buffer all the log messages it receives, up until a configured threshold of number of messages of a certain lever is reached, after it will pass all log messages to the wrapped handler. Useful for applying in batch processing when you're only interested in significant failures instead of minor, single erroneous events.
<?php
return [
'monolog' => [
'handlers' => [
'myHandlerName' => [
'type' => 'overflow',
'options' => [
'handler' => 'my-handler', // Required: Registered Handler to wrap
'thresholdMap' => [ // Optional: Number of records of each level to buffer before passing them on
'debug' => 0,
'info' => 0,
'notice' => 0,
'warning' => 0,
'error' => 0,
'critical' => 0,
'alert' => 0,
'emergency' => 0,
],
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this handler will be triggered. Must be a \Monolog\Level
'bubble' => true, // Optional: Whether the messages that are handled can bubble up the stack or not
],
],
],
],
];
Monolog Docs: OverflowHandler
LogMonsterHandler
A dead man's switch for cron jobs, workers, or code paths that should always log. The monster watches the records go
by, and if it has not been fed at least hunger records by the time it is closed, it sends a complaint record to the
handler it wraps. The records it watches are not passed on.
<?php
return [
'monolog' => [
'handlers' => [
'myHandlerName' => [
'type' => 'logMonster',
'options' => [
'handler' => 'my-handler', // Required: Registered Handler to send the complaint to
'hunger' => 10, // Required: Number of records the monster must see before it is closed
'angerLevel' => \Monolog\Level::Error, // Optional: The level of the complaint record. Must be a \Monolog\Level
'channel' => 'log-monster', // Optional: The channel of the complaint record
'wantsContextChips' => false, // Optional: If true, only records with context count towards the hunger
],
],
],
],
];
Monolog Docs: LogMonsterHandler
Formatters
LineFomatter
Formats a log record into a one-line string.
<?php
return [
'monolog' => [
'formatters' => [
'myFormatterName' => [
'type' => 'line',
'options' => [
'format' => null, // Optional: The format of the message
'dateFormat' => null, // 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: Whether to omit empty context and extra arrays
'includeStacktraces' => false, // Optional: Whether to include the stack traces of exceptions
],
],
],
],
];
Monolog Docs: LineFormatter
HtmlFormatter
Used to format log records into a human readable html table, mainly suitable for emails.
<?php
return [
'monolog' => [
'formatters' => [
'myFormatterName' => [
'type' => 'html',
'options' => [
'dateFormat' => null, // Optional: The format of the timestamp: one supported by DateTime::format
],
],
],
],
];
Monolog Docs: HtmlFormatter
NormalizerFormatter
Normalizes objects/resources down to strings so a record can easily be serialized/encoded.
<?php
return [
'monolog' => [
'formatters' => [
'myFormatterName' => [
'type' => 'normalizer',
'options' => [
'dateFormat' => null, // Optional: The format of the timestamp: one supported by DateTime::format
],
],
],
],
];
Monolog Docs: NormalizerFormatter
ScalarFormatter
Used to format log records into an associative array of scalar values.
<?php
return [
'monolog' => [
'formatters' => [
'myFormatterName' => [
'type' => 'scalar',
'options' => [], // No options available
],
],
],
];
Monolog Docs: ScalarFormatter
JsonFormatter
Encodes a log record into json.
<?php
return [
'monolog' => [
'formatters' => [
'myFormatterName' => [
'type' => 'json',
'options' => [
'batchMode' => \Monolog\Formatter\JsonFormatter::BATCH_MODE_JSON, // Optional: JsonFormatter::BATCH_MODE_JSON or JsonFormatter::BATCH_MODE_NEWLINES
'appendNewline' => true, // Optional: Whether to append a newline after each record
'ignoreEmptyContextAndExtra' => false, // Optional: Whether to omit empty context and extra arrays
'includeStacktraces' => false, // Optional: Whether to include the stack traces of exceptions
],
],
],
],
];
Monolog Docs: JsonFormatter
WildfireFormatter
Used to format log records into the Wildfire/FirePHP protocol, only useful for the FirePHPHandler.
<?php
return [
'monolog' => [
'formatters' => [
'myFormatterName' => [
'type' => 'wildfire',
'options' => [
'dateFormat' => null, // Optional: The format of the timestamp: one supported by DateTime::format
],
],
],
],
];
Monolog Docs: WildfireFormatter
ChromePHPFormatter
Used to format log records into the ChromePHP format, only useful for the ChromePHPHandler.
<?php
return [
'monolog' => [
'formatters' => [
'myFormatterName' => [
'type' => 'chromePHP',
'options' => [], // No options available
],
],
],
];
Monolog Docs: ChromePHPFormatter
GelfMessageFormatter
Used to format log records into Gelf message instances, only useful for the GelfHandler.
<?php
return [
'monolog' => [
'formatters' => [
'myFormatterName' => [
'type' => 'gelf',
'options' => [
'systemName' => null, // Optional: The name of the system for the Gelf log message. null uses the hostname of the machine
'extraPrefix' => null, // Optional: a prefix for 'extra' fields from the Monolog record
'contextPrefix' => 'ctxt_', // Optional: a prefix for 'context' fields from the Monolog record
'maxLength' => null, // Optional: Length per field
],
],
],
],
];
Monolog Docs: GelfMessageFormatter
LogstashFormatter
Used to format log records into logstash event json, useful for any handler listed under inputs here.
<?php
return [
'monolog' => [
'formatters' => [
'myFormatterName' => [
'type' => 'logstash',
'options' => [
'applicationName' => 'app-name', // Required: the application that sends the data, used as the "type" field of logstash
'systemName' => null, // Optional: The system/machine name, used as the "source" field of logstash. null uses the hostname of the machine
'extraKey' => 'extra', // Optional: Key name used for the 'extra' fields in the logstash document
'contextKey' => 'context', // Optional: Key name used for the 'context' fields in the logstash document
],
],
],
],
];
Monolog Docs: LogstashFormatter
ElasticaFormatter
Used to format log records into logstash event json, useful for any handler listed under inputs here.
<?php
return [
'monolog' => [
'formatters' => [
'ElasticaFormatter' => [
'type' => 'elastica',
'options' => [
'index' => 'some-index', // Required: Elastic search index name
'type' => null, // Optional: Elastic search document type. Unused since Elasticsearch 7
],
],
],
],
];
Monolog Docs: ElasticaFormatter
LogglyFormatter
Used to format log records into Loggly messages, only useful for the LogglyHandler.
<?php
return [
'monolog' => [
'formatters' => [
'myFormatterName' => [
'type' => 'loggly',
'options' => [
'batchMode' => \Monolog\Formatter\LogglyFormatter::BATCH_MODE_NEWLINES, // Optional: LogglyFormatter::BATCH_MODE_JSON or LogglyFormatter::BATCH_MODE_NEWLINES
'appendNewline' => false, // Optional: Whether to append a newline after each record
],
],
],
],
];
Monolog Docs: LogglyFormatter
FlowdockFormatter
Deprecated: Monolog deprecated the FlowdockFormatter in 3.3.0 as Flowdock has shut down. This factory will be removed when this library adds Monolog 4 support.
Used to format log records into Flowdock messages, only useful for the FlowdockHandler.
<?php
return [
'monolog' => [
'formatters' => [
'myFormatterName' => [
'type' => 'flowdock',
'options' => [
'source' => 'value', // Required: Human readable identifier of the application
'sourceEmail' => 'value', // Required: Email address of the message sender
],
],
],
],
];
Monolog Docs: FlowdockFormatter
MongoDBFormatter
Converts \DateTime instances to \MongoDate and objects recursively to arrays, only useful with the MongoDBHandler.
<?php
return [
'monolog' => [
'formatters' => [
'myFormatterName' => [
'type' => 'mongodb',
'options' => [
'maxNestingLevel' => 3, // Optional: 0 means infinite nesting, the record itself is level 1, the record's context is 2
'exceptionTraceAsString' => true, // Optional: Set to false to log exception traces as sub documents instead of strings
],
],
],
],
];
Monolog Docs: MongoDBFormatter
LogmaticFormatter
User to format log records to Logmatic messages, only useful for the LogmaticHandler.
<?php
return [
'monolog' => [
'formatters' => [
'myFormatterName' => [
'type' => 'logmatic',
'options' => [
'batchMode' => \Monolog\Formatter\LogmaticFormatter::BATCH_MODE_JSON, // Optional: LogmaticFormatter::BATCH_MODE_JSON or LogmaticFormatter::BATCH_MODE_NEWLINES
'appendNewline' => true, // Optional: Whether to append a newline after each record
'hostname' => '', // Optional: 'hostname' parameter for indexing by Logmatic
'appName' => '', // Optional: 'appname' parameter for indexing by Logmatic
],
],
],
],
];
Monolog Docs: LogmaticFormatter
FluentdFormatter
Serializes a log message to Fluentd's unix socket protocol. Configure Fluentd with the unix input to receive
the messages, e.g. using a SocketHandler pointed at the Fluentd socket.
<?php
return [
'monolog' => [
'formatters' => [
'myFormatterName' => [
'type' => 'fluentd',
'options' => [
'levelTag' => false, // Optional: Whether to append the level name to the tag, e.g. "app.error" instead of "app"
],
],
],
],
];
Monolog Docs: FluentdFormatter
GoogleCloudLoggingFormatter
Encodes log records as JSON in the structured logging
format Google Cloud Logging expects, with severity and time keys in place of the level and datetime keys.
<?php
return [
'monolog' => [
'formatters' => [
'myFormatterName' => [
'type' => 'googleCloudLogging',
'options' => [
'batchMode' => \Monolog\Formatter\GoogleCloudLoggingFormatter::BATCH_MODE_JSON, // Optional: GoogleCloudLoggingFormatter::BATCH_MODE_JSON or GoogleCloudLoggingFormatter::BATCH_MODE_NEWLINES
'appendNewline' => true, // Optional: Whether to append a newline after each record
'ignoreEmptyContextAndExtra' => false, // Optional: Whether to omit empty context and extra arrays
'includeStacktraces' => false, // Optional: Whether to include the stack traces of exceptions
],
],
],
],
];
Monolog Docs: GoogleCloudLoggingFormatter
SyslogFormatter
Formats log records as RFC 5424 syslog messages, adding the hostname, application name and process ID to each line. Useful with a StreamHandler writing to a file or stream that a syslog daemon reads.
<?php
return [
'monolog' => [
'formatters' => [
'myFormatterName' => [
'type' => 'syslog',
'options' => [
'applicationName' => '-', // Optional: APP-NAME field of the syslog message. '-' is the syslog NILVALUE
],
],
],
],
];
Monolog Docs: SyslogFormatter
ElasticsearchFormatter
Used to format log records into Elasticsearch documents, only useful for the ElasticsearchHandler.
<?php
return [
'monolog' => [
'formatters' => [
'myFormatterName' => [
'type' => 'elasticsearch',
'options' => [
'index' => 'some-index', // Required: Elasticsearch index name
'type' => '_doc', // Required: Elasticsearch document type. Only sent to Elasticsearch versions before 7, use '_doc' otherwise
],
],
],
],
];
Monolog Docs: ElasticsearchFormatter
RedactingFormatter
Wraps another formatter and masks secrets in its output. The values of the sensitive context and extra keys are
masked, and are then also removed wherever else they show up in the output, e.g. in the message. Values passed to
a constructor parameter marked #[\SensitiveParameter] of any object in the record are removed too, and the
patterns are applied to the output last.
<?php
return [
'monolog' => [
'formatters' => [
'myFormatterName' => [
'type' => 'redacting',
'options' => [
'formatter' => 'my-formatter', // Required: Registered Formatter to wrap
'sensitiveKeys' => ['password', 'passwd', 'pwd', 'secret', 'token', 'api_key', 'apikey', 'authorization', 'auth', 'cookie'], // Optional: Context and extra keys whose values are masked, case-insensitive
'patterns' => [], // Optional: PCRE patterns to mask in the output, e.g. \Monolog\Formatter\RedactingFormatter::TOKEN_PATTERN
'mask' => '[REDACTED]', // Optional: Replacement for the masked values
'redactSensitiveParameters' => true, // Optional: Whether to also remove the values of #[\SensitiveParameter] constructor parameters. Reflects on every object in the record
'minSecretLength' => 5, // Optional: Secrets shorter than this are masked under their key, but not removed from the rest of the output
],
],
],
],
];
Monolog Docs: RedactingFormatter
Processors
PsrLogMessageProcessor
Processes a log record's message according to PSR-3 rules, replacing {foo} with the value from $context['foo'].
<?php
return [
'monolog' => [
'processors' => [
'myProcessorsName' => [
'type' => 'psrLogMessage',
'options' => [
'dateFormat' => null, // Optional: The format used for date placeholders. null uses Monolog's default
'removeUsedContextFields' => false, // Optional: Whether to remove the context fields used as placeholders
],
],
],
],
];
Monolog Docs: PsrLogMessageProcessor
IntrospectionProcessor
Adds the line/file/class/method from which the log call originated.
<?php
return [
'monolog' => [
'processors' => [
'myProcessorsName' => [
'type' => 'introspection',
'options' => [
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this processor will be triggered. Must be a \Monolog\Level
'skipClassesPartials' => [], // Optional: Class name prefixes to skip when looking for the caller
'skipStackFramesCount' => 0, // Optional: Number of stack frames to skip
],
],
],
],
];
Monolog Docs: IntrospectionProcessor
WebProcessor
Adds the current request URI, request method and client IP to a log record.
<?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' => ['url' => 'REQUEST_URI'], // 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 Docs: WebProcessor
MemoryUsageProcessor
Adds the current memory usage to a log record.
<?php
return [
'monolog' => [
'processors' => [
'myProcessorsName' => [
'type' => 'memoryUsage',
'options' => [
'realUsage' => true, // Optional: Whether to report the real memory allocated by the system
'useFormatting' => true, // Optional: Whether to format the value with a unit, e.g. '1.5 MB'
],
],
],
],
];
Monolog Docs: MemoryUsageProcessor
MemoryPeakUsageProcessor
Adds the peak memory usage to a log record.
<?php
return [
'monolog' => [
'processors' => [
'myProcessorsName' => [
'type' => 'memoryPeak',
'options' => [
'realUsage' => true, // Optional: Whether to report the real memory allocated by the system
'useFormatting' => true, // Optional: Whether to format the value with a unit, e.g. '1.5 MB'
],
],
],
],
];
Monolog Docs: MemoryPeakUsageProcessor
ProcessIdProcessor
Adds the process id to a log record.
<?php
return [
'monolog' => [
'processors' => [
'myProcessorsName' => [
'type' => 'processId',
'options' => [], // No options
],
],
],
];
Monolog Docs: ProcessIdProcessor
UidProcessor
Adds a unique identifier to a log record.
<?php
return [
'monolog' => [
'processors' => [
'myProcessorsName' => [
'type' => 'uid',
'options' => [
'length' => 7, // Optional: The uid length. Must be an integer between 1 and 32
],
],
],
],
];
Monolog Docs: UidProcessor
GitProcessor
Adds the current git branch and commit to a log record.
Note: Only works if the git executable is in your working path.
<?php
return [
'monolog' => [
'processors' => [
'myProcessorsName' => [
'type' => 'git',
'options' => [
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this processor will be triggered. Must be a \Monolog\Level
],
],
],
],
];
Monolog Docs: GitProcessor
MercurialProcessor
Adds the current hg branch and commit to a log record.
Note: Only works if the hg executable is in your working path.
<?php
return [
'monolog' => [
'processors' => [
'myProcessorsName' => [
'type' => 'mercurial',
'options' => [
'level' => \Monolog\Level::Debug, // Optional: The minimum logging level at which this processor will be triggered. Must be a \Monolog\Level
],
],
],
],
];
Monolog Docs: MercurialProcessor
TagProcessor
Adds an array of predefined tags to a log record.
<?php
return [
'monolog' => [
'processors' => [
'myProcessorsName' => [
'type' => 'tags',
'options' => [
'tags' => [], // Optional: Array of tags to add to records
],
],
],
],
];
Monolog Docs: TagProcessor
HostnameProcessor
Adds the current hostname to a log record.
<?php
return [
'monolog' => [
'processors' => [
'myProcessorsName' => [
'type' => 'hostname',
'options' => [], // No options
],
],
],
];
Monolog Docs: HostnameProcessor
ClosureContextProcessor
Generates the context from a closure when the closure is the only value in the context, e.g.
$logger->debug('message', [fn () => ['expensive' => $data]]). Added to a handler, the context is only generated
when that handler logs the record, which is useful behind the FingersCrossedHandler or other filtering handlers.
<?php
return [
'monolog' => [
'processors' => [
'myProcessorsName' => [
'type' => 'closureContext',
'options' => [], // No options
],
],
],
];
Monolog Docs: ClosureContextProcessor
LoadAverageProcessor
Adds the system load average to a log record.
<?php
return [
'monolog' => [
'processors' => [
'myProcessorsName' => [
'type' => 'loadAverage',
'options' => [
'avgSystemLoad' => \Monolog\Processor\LoadAverageProcessor::LOAD_1_MINUTE, // Optional: LoadAverageProcessor::LOAD_1_MINUTE, LoadAverageProcessor::LOAD_5_MINUTE or LoadAverageProcessor::LOAD_15_MINUTE
],
],
],
],
];
Monolog Docs: LoadAverageProcessor
Upgrades
Upgrading from version 5 to 6
Version 6 supports Monolog 3 and validates every configuration option.
Requirements
- PHP 8.4 or later.
- Monolog 3.12 or later.
psr/container1.1 or 2.0.
Configuration
- Levels must be
\Monolog\Levelenum cases, e.g.\Monolog\Level::Errorinstead of\Monolog\Logger::ERROR. This applies toleveland every other level option (deduplicationLevel,maxLevel,minLevelOrList,passthruLevel,activationStrategy,highPriorityLevelandemergencyLevel). - Options are validated before the handler, formatter or processor is created. A value of the wrong type
throws
InvalidConfigException, and a missing required option throwsMissingConfigException, naming the option. Boolean options must be real booleans, and numeric options must be numbers or numeric strings. - Options Monolog has no default for are now required, e.g.
tokenfor the Slack, Pushover, Loggly, LogEntries, InsightOps, Logmatic and FleepHook handlers;identfor the SyslogHandler; and theto,fromandsubjectoptions for the NativeMailer and SendGrid handlers. - Defaults now match Monolog's defaults:
leveldefaults to\Monolog\Level::Criticalfor the Slack, SlackWebhook and Pushover handlers, and to\Monolog\Level::Errorfor the NativeMailer, SendGrid, IFTTT and NewRelic handlers. All other handlers from version 5 still default to\Monolog\Level::Debug.- StreamHandler:
useLockingdefaults tofalseandfilePermissiontonull. - BufferHandler:
flushOnOverflowdefaults tofalse. - AmqpHandler:
exchangeNamedefaults tonull. - InsightOpsHandler:
regiondefaults to'us'. - LogglyFormatter:
appendNewlinedefaults tofalse.
- SocketHandler: the
writeTimeoutoption is removed.timeout,writingTimeoutandconnectionTimeoutnow map directly to Monolog's options of the same name. - LogstashFormatter:
extraPrefixandcontextPrefixare replaced byextraKeyandcontextKey, following Monolog 3. - OverflowHandler: the wrapped handler is configured with
handler; the README previously showedhandlers. - New options are available for the Monolog 3 constructor parameters. For example, the socket based handlers
accept
persistent,timeout,writingTimeout,connectionTimeoutandchunkSize, and the RotatingFileHandler acceptsdateFormat,filenameFormatandtimezone. See each handler above.
New in version 6
Factories for Monolog handlers, formatters and processors that version 5 did not support:
- Handlers: FrankenPhpHandler, SymfonyMailerHandler, RollbarHandler, RedisPubSubHandler, ElasticsearchHandler and LogMonsterHandler.
- Formatters: FluentdFormatter, GoogleCloudLoggingFormatter, SyslogFormatter, ElasticsearchFormatter and RedactingFormatter.
- Processors: ClosureContextProcessor and LoadAverageProcessor.
Custom formatter factories can implement FormatterManagerAwareInterface, using FormatterManagerTrait, to get
other configured formatters from the FormatterManager, the same way HandlerManagerAwareInterface gives handler
factories the HandlerManager.
Removed
- SwiftMailerHandler: removed from Monolog 3, which replaces it with the SymfonyMailerHandler.
- MandrillHandler: it still requires SwiftMailer in Monolog 3, which is no longer maintained.
- DoctrineCouchDBHandler: doctrine/couchdb cannot be installed on supported PHP versions. The CouchDBHandler is still available.
- PHPConsoleHandler: Monolog 3 deprecated it, and php-console/php-console is abandoned and cannot be loaded on PHP 8 without warnings.
Deprecated
These factories still work, but Monolog 3 deprecated the classes they create, and they will be removed when this library adds Monolog 4 support:
- CubeHandler: Cube appears abandoned.
- FlowdockHandler and FlowdockFormatter: Flowdock has shut down.
Code changes
FactoryInterface::__invoke()now declares anobjectreturn type, andContainerAwareInterface::setContainer()andHandlerManagerAwareInterface::setHandlerManager()declarevoid. Update any custom factories to match.MonologFactory::setChannelName()is removed; pass the channel name to the constructor instead, e.g.new MonologFactory('channelTwo').getChannelName()is no longer static, andsetChannelChanger()now takes the container as its first argument.- Bug fixes: the CouchDBHandler now reads
dbname(it readport), the SyslogUdpHandler now readsport(it readhost), and the FallbackGroupHandler and WhatFailureGroupHandler factories now receive the handler manager.
Older releases
Backwards compatibility breaks
- Updated all namespaces from Blazon to Blazon as the list of contributors has expanded beyond just myself. This move I believe will help ensure forward compatibility and allow these libraries to stay well maintained well into the future.