yii2 - Yii2 save 登录数据库
问题描述
我对使用 Yii2 的日志有一些问题。我以这种方式设置日志目标:
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'flushInterval' => 1,//test
'targets' => [
[
'class' => 'common\components\SaDbTarget',
'levels' => ['error', 'warning','trace','info'],
'exportInterval' => 1,//test
//'categories' => ['application'],
/*'except' => [
'yii\db\*',
],*/
],
],
],
我创建了扩展 DbTarget 类的 SaDbTarget,这工作正常,因为我在表中找到了一些日志。之后,在控制器中,我尝试像这样设置日志
public function actionIndex(){
$searchModel = new CategorySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
Yii::trace('trace log', __METHOD__);
Yii::warning('warning log');
// here is the rest of the code
}
我可以在调试工具栏中看到这 2 个日志,但在我的数据库表中看不到。根据文档
要使每条日志消息立即出现在日志目标中,您应该将 flushInterval 和 exportInterval 都设置为 1
我试图设置这个值,但仍然不起作用。
我不知道我做错了什么。
更新这是我的 SaDbTarget
namespace common\components;
use Yii;
use yii\log\DbTarget;
use yii\log\Logger;
class SaDbTarget extends DbTarget{
//set custom table db for saving log
public $logTable = 'authlog';
//overwrite export();
public function export(){
$tableName = $this->db->quoteTableName($this->logTable);
$sql = "INSERT INTO $tableName ([[authlog_login]], [[authlog_ip]], [[authlog_area]], [[authlog_act]], [[authlog_time]], [[authlog_data]])
VALUES (:login, :ip, :area, :act, :time, :data )";
$command = $this->db->createCommand($sql);
//Get username
$user=Yii::$app->user->getId();
//Get user ip address
$ip = Yii::$app->request->getUserIP();
//Get area/controller
$controller=Yii::$app->controller->uniqueId;
//Get action
$event= Yii::$app->controller->module->requestedAction->id;
//Set timezone
$time = Yii::$app->formatter->asDate('now', 'php:Y-m-d H:i:s');
//Set Data
$data = $this->messages[0];
$command->bindValues([
':login' => $user,
':ip' => $ip,
':area' => $controller,
':act' => $event,
':time' => $time,
':data' => $data,
])->execute();
}
解决方案
推荐阅读
- excel - 如何返回最近收到的电子邮件?
- python - 如何将参差不齐的张量与“矩形”张量连接起来?
- html - html媒体查询在iphone设备中不起作用
- netlogo - 如何在 NetLogo 中导出数组或有序表
- python - 如何总结Python中列表列表中的列?
- docker - 代码隔离:Windows AppContainer 与 Docker
- python - 扩展 django 用户模型(无法添加额外字段)
- date - 如果单元格为空,如何添加今天的日期,如果没有跳到下一列?
- python - 匹配中文单词的正则表达式,不包括匹配单词开头和结尾的其他单词
- nim-lang - 最终从 STDIN 读取压缩文件:正确的方法是什么?