Monolog

了解如何启用 Sentry 的 PHP SDK 以捕获 Monolog 事件。

当使用 Monolog 时,您可以配置一个 面包屑 处理程序,以将 Monolog 消息捕获为面包屑,并配置一个处理程序以将消息作为事件发送到 Sentry。 面包屑处理程序不会直接向 Sentry 发送任何内容,它只会记录面包屑,这些面包屑将附加到发送到 Sentry 的任何事件或异常中。

Copied
<?php

use Monolog\Level;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// Setup the Sentry SDK, this can also be done elsewhere in your application
\Sentry\init([
    'dsn' => 'https://examplePublicKey@o0.ingest.sentry.io/0'
]);

// Create a Monolog channel with a breadcrumb handler and a Sentry handler
$log = new Logger('sentry');
$log->pushHandler(new \Sentry\Monolog\BreadcrumbHandler(
    hub: \Sentry\SentrySdk::getCurrentHub(),
    level: Level::Info, // Take note of the level here, messages with that level or higher will be attached to future Sentry events as breadcrumbs
));
$log->pushHandler(new \Sentry\Monolog\Handler(
    hub: \Sentry\SentrySdk::getCurrentHub(),
    level: Level::Error, // Take note of the level here, messages with that level or higher will be sent to Sentry
    bubble: true,
    fillExtraContext: false, // Will add a `monolog.context` & `monolog.extra`, key to the event with the Monolog `context` & `extra` values
));

// Log an error:
$log->error('Something bad happened');

// To log an exception you can use the following code:
try {
    throw new RuntimeException('Some exception');
} catch (RuntimeException $exception) {
    $log->error('Some exception happened', ['exception' => $exception]);
}