PHP code example of liwenyu / yii2-masked-log
1. Go to this page and download the library: Download liwenyu/yii2-masked-log library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
liwenyu / yii2-masked-log example snippets
// common/config/params.php 或 main-local.php 中合并
'params' => [
'logMask' => [
'enabled' => true, // 是否启用脱敏,false 时不做任何脱敏
'mask_keys' => [ // 日志消息为数组时,这些键对应的值会被替换为 ***
'password',
'pwd',
'token',
'secret',
'auth_key',
'access_token',
],
'mask_vars' => [ // 上下文变量(如 _GET、_POST)中要脱敏的项,支持点分路径
'_POST.password',
'_GET.token',
'_SERVER.HTTP_AUTHORIZATION',
'_SERVER.PHP_AUTH_USER',
'_SERVER.PHP_AUTH_PW',
],
],
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'liwenyu\maskedlog\MaskedFileTarget',
'logFile' => '@runtime/logs/app.log',
'levels' => ['error', 'warning', 'info'],
],
[
'class' => 'liwenyu\maskedlog\MaskedFileTarget',
'logFile' => '@runtime/logs/request.log',
'levels' => ['info', 'trace'],
'categories' => ['Request', 'Response'],
'logVars' => ['_GET', '_POST', '_SERVER'],
],
],
],
[
'class' => 'liwenyu\maskedlog\MaskedFileTarget',
'logFile' => '@runtime/logs/app.log',
'maskEnabled' => true,
'maskKeys' => ['password', 'pwd', 'token'],
'maskVars' => ['_POST.password', '_GET.token'],
],
// 数组中的 password、token 会变成 *** 再写入日志
Yii::info([
'username' => 'zhangsan',
'password' => '123456',
'token' => 'secret-token-xxx',
], 'login');
// 嵌套数组中的指定键也会被脱敏
Yii::info([
'action' => 'register',
'data' => [
'name' => 'lisi',
'password' => 'abc123',
],
], 'user');
use liwenyu\maskedlog\MaskedFileTarget;
$raw = 'POST /api/v2/users, Params=user_name=test&user_password=123456';
$safe = MaskedFileTarget::maskLogString($raw);
// $safe = 'POST /api/v2/users, Params=user_name=test&user_password=***'
file_put_contents($logFile, $safe . "\n", FILE_APPEND);
bash
php yii script/masked-log-test