All you need to log with Bref on AWS Lambda.
Bref/Logger is a lightweight PSR-3 logger for AWS Lambda. Messages are sent to stderr so that they end up in CloudWatch.
As explained in the Bref documentation, logging in AWS Lambda means logging to stderr. Logs written to stderr are automatically sent to CloudWatch, AWS' solution to collect and view logs.
While classic loggers like Monolog work fine, this logger comes as a simpler and lighter alternative optimized for AWS Lambda. It does not require any configuration and currently contains a single class.
Since it is PSR-3 compliant, Bref/Logger is also compatible with any framework or library consuming a PSR-3 logger.
composer require bref/logger
The logger does not require any configuration:
$logger = new \Bref\Logger\StderrLogger();By default, messages above the info level will be logged, the rest will be discarded.
It is possible to log using any PSR-3 log level, the most common ones being:
$logger->debug('This is a debug message');
$logger->info('This is an info');
$logger->warning('This is a warning');
$logger->error('This is an error');8f507cfc-8b35-4e7e-9f26-f2a3a6e7e1a2 INFO This is an info {"message":"This is an info","level":"INFO"}
8f507cfc-8b35-4e7e-9f26-f2a3a6e7e1a2 WARNING This is a warning {"message":"This is a warning","level":"WARNING"}
8f507cfc-8b35-4e7e-9f26-f2a3a6e7e1a2 ERROR This is an error {"message":"This is an error","level":"ERROR"}
This follows the standard format used by official AWS Lambda runtimes. For example the initial request ID is recognized by CloudWatch so that filter @requestId = '8f507cfc-...' shows all the logs of a single request/invocation.
Messages under info are not logged.
PSR-3 placeholders can be used to insert information from the $context array into the message without having to concatenate strings manually:
$logger->warning('Invalid login attempt for email {email}', [
'email' => $email,
]);WARNING Invalid login attempt for email johndoe@example.com {"message":"Invalid login attempt for email johndoe@example.com","level":"WARNING","context":{"email":"johndoe@example.com"}}
Exceptions can be logged under the exception key:
try {
// ...
} catch (\Exception $e) {
$logger->error('Impossible to complete the action', [
'exception' => $e,
]);
}ERROR Impossible to complete the action {"message":"Impossible to complete the action","level":"ERROR","exception":{"class":"InvalidArgumentException","message":"Impossible to complete the action","code":0,"file":"/var/task/index.php","line":12,"trace":[{"file":"/var/task/index.php","line":86,"function":"main"}]}
It is possible to change the level above which messages are logged.
For example to log all messages:
$logger = new \Bref\Logger\StderrLogger(\Psr\Log\LogLevel::DEBUG);