Awesome
middlewares/reporting-logger
Middleware to log server-side reportings, like CSP messages or any javascript error. More info about how collect javascript errors. You may need also the middlewares/payload (or any other middleware with the same purpose) to parse the json of the body.
Requirements
- PHP >= 7.2
- A PSR-7 http library
- A PSR-15 middleware dispatcher
- A PSR-3 logger library
Installation
This package is installable and autoloadable via Composer as middlewares/reporting-logger.
composer require middlewares/reporting-logger
Example
Register a error handler in your javascript code:
window.onerror = function (message, file, lineNo, colNo) {
const error = { message, file, lineNo, colNo };
const blob = new Blob([ JSON.stringify(error) ], { type: 'application/json' });
navigator.sendBeacon('/report', blob);
}
Dispatcher::run([
new Middlewares\JsonPayload(),
new Middlewares\ReportingLogger($logger)
]);
Usage
You need a Psr\Log\LoggerInterface
instance to handle the logs, for example, monolog
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$logger = new Logger('access');
$logger->pushHandler(new StreamHandler('data/logs.txt'));
Dispatcher::run([
new Middlewares\ReportingLogger($logger)
]);
Optionally, you can provide a Psr\Http\Message\ResponseFactoryInterface
as the second argument, that will be used to create the responses returned after handle the reporting. If it's not defined, Middleware\Utils\Factory will be used to detect it automatically.
$responseFactory = new MyOwnResponseFactory();
$reporting = new Middlewares\ReportingLogger($logger, $responseFactory);
path
The uri path where the logs will be reported. By default is /report
.
// In front-end: send the error to "/log-reporting" path
navigator.sendBeacon('/log-reporting', error);
// In back-end: configure to collect all reportings send to the same path
$reporting = (new Middlewares\ReportingLogger($logger))->path('/log-reporting')
message
The message used to save the logs. You can use the strings %{varname}
to generate dinamic messages using the reporting data. For example:
$reporting = (new Middlewares\ReportingLogger($logger))
->message('New error: "%{message}" in line %{lineNumber}, column %{colNumber}')
]);
Please see CHANGELOG for more information about recent changes and CONTRIBUTING for contributing details.
The MIT License (MIT). Please see LICENSE for more information.