notamedia / yii2-sentry
为 Sentry 定制的 Yii2 日志记录器
1.7.0
2021-01-12 15:17 UTC
Requires
- php: ^7.2|^8.0
- sentry/sdk: ^3.0
- yiisoft/yii2: ^2.0
Requires (Dev)
- codeception/codeception: ^4.0
- codeception/module-asserts: ^1.3
- codeception/module-yii2: ^1.1
This package is auto-updated.
Last update: 2024-09-08 20:15:20 UTC
README
安装
composer require notamedia/yii2-sentry
在应用程序配置中添加目标类
return [ 'components' => [ 'log' => [ 'traceLevel' => YII_DEBUG ? 3 : 0, 'targets' => [ [ 'class' => 'notamedia\sentry\SentryTarget', 'dsn' => 'http://2682ybvhbs347:235vvgy465346@sentry.io/1', 'levels' => ['error', 'warning'], // Write the context information (the default is true): 'context' => true, // Additional options for `Sentry\init`: 'clientOptions' => ['release' => 'my-project-name@2.3.12'] ], ], ], ], ];
用法
编写简单的消息
\Yii::error('message', 'category');
包含额外数据的消息
\Yii::warning([ 'msg' => 'message', 'extra' => 'value', ], 'category');
额外回调
extraCallback
属性可以作为一个可调用函数来修改额外数据
'targets' => [ [ 'class' => 'notamedia\sentry\SentryTarget', 'dsn' => 'http://2682ybvhbs347:235vvgy465346@sentry.io/1', 'levels' => ['error', 'warning'], 'context' => true, // Write the context information. The default is true. 'extraCallback' => function ($message, $extra) { // some manipulation with data $extra['some_data'] = \Yii::$app->someComponent->someMethod(); return $extra; } ], ],
标签
在消息中添加额外标签。如果需要为事件添加额外标签,请在消息中添加 tags
键。标签是各种键/值对,它们被分配给一个事件,以后可以用作事件的细分或快速访问相关事件。
示例
\Yii::warning([ 'msg' => 'message', 'extra' => 'value', 'tags' => [ 'extraTagKey' => 'extraTagValue', ] ], 'category');
有关标签的更多信息,请参阅 https://docs.sentry.io/learn/context/#tagging-events
附加上下文
您可以通过在记录之前调用 \Sentry\configureScope()
来添加附加上下文(例如用户信息、指纹等)。例如,在主配置中的 beforeAction
事件上(实际位置取决于您的项目)
return [ // ... 'on beforeAction' => function (\yii\base\ActionEvent $event) { /** @var \yii\web\User $user */ $user = Yii::$app->has('user', true) ? Yii::$app->get('user', false) : null; if ($user && ($identity = $user->getIdentity(false))) { \Sentry\configureScope(function (\Sentry\State\Scope $scope) use ($identity) { $scope->setUser([ // User ID and IP will be added by logger automatically 'username' => $identity->username, 'email' => $identity->email, ]); }); } return $event->isValid; }, // ... ];
日志级别
Yii2 日志级别转换为 Sentry 级别
\yii\log\Logger::LEVEL_ERROR => 'error',
\yii\log\Logger::LEVEL_WARNING => 'warning',
\yii\log\Logger::LEVEL_INFO => 'info',
\yii\log\Logger::LEVEL_TRACE => 'debug',
\yii\log\Logger::LEVEL_PROFILE_BEGIN => 'debug',
\yii\log\Logger::LEVEL_PROFILE_END => 'debug',