yujin1st/yii2-sentry

Yii2 适用于 Sentry 的日志记录器

安装: 9

依赖: 0

建议者: 0

安全: 0

星标: 0

关注者: 0

分支: 50

类型:yii2-extension

v1.9 2024-06-24 17:47 UTC

This package is auto-updated.

Last update: 2024-09-24 18:23:19 UTC


README

Build Status Latest Stable Version Total Downloads License

安装

composer require yujin1st/yii2-sentry

在应用配置中添加目标类

return [
    'components' => [
	    'log' => [
		    'traceLevel' => YII_DEBUG ? 3 : 0,
		    'targets' => [
			    [
				    'class' => 'yujin1st\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' => 'yujin1st\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',