• yii 日志和事件


    日志

    配置

    'log' => [
        'traceLevel' => YII_DEBUG ? 3 : 0,
        'targets' => [
            [
                'class' => 'yiilogFileTarget',
                'levels' => ['error', 'warning'],
            ],
    
            //以文件的方式记录
            [
                'class' => 'yiilogFileTarget',
                'levels' => ['info'],
                'categories' => ['shopify'],
                'logVars' => ['*'],//不记录PHP全局变量$_POST等
                'logFile' => '@runtime/logs/shopify.log',
    //                    'exportInterval' => 1,//在导出消息之前应该累积多少条消息
                'maxFileSize' => 1024 * 2,//文件大小
                'maxLogFiles' => 20,
            ],
    
            //以邮件的方式记录,这种方式后面还需设置邮箱的账号密码和host
            [
                'class' => 'yiilogEmailTarget',
                'levels' => ['info'],
                'categories' => ['shopify'],
                'logVars' => ['*'],//不记录PHP全局变量$_POST等
                'message' => [
                    'from' => ['service@hjk.top'],
                    'to' => ['yowwoy@hjk.com'],
                    'subject' => '商城预警',
                ],
            ],
        ],
    ],
            'mailer' => [
        'class' => 'yiiswiftmailerMailer',
        'viewPath' => '@common/mail',
        // send all mails to a file by default. You have to set
        // 'useFileTransport' to false and configure a transport
        // for the mailer to send real emails.
        'useFileTransport' => false,
        'transport' => [
            'class' => 'Swift_SmtpTransport',
            'host' => 'smtp.exmail.qq.com',//邮箱服务器
            'username' => 'service@hjk.top',//用户名
            'password' => 'hujikhllkj',//密码
            'port' => '465',//端口
            'encryption' => 'ssl',//加密
        ],
        'messageConfig'=>[
            'charset'=>'UTF-8',
            'from'=>['hguhjl@163.com'=>'admin']
        ],
    ],

    测试调用

        public function actionLog1()
        {
            Yii::info("出错啦,出错啦", 'shopify');
    
            Yii::getLogger()->log("自定义日志",Logger::LEVEL_ERROR);
    
            Yii::trace("trace,开发调试时候记录");
    
            Yii::error("error,错误日志");
    
            Yii::warning("warning,警告信息");
    
            Yii::info("info,记录操作提示");
        }

    事件

    配置

          //添加事件
        'on beforeRequest' => function($event) {
            yiiaseEvent::on(yiidbBaseActiveRecord::className(), yiidbBaseActiveRecord::EVENT_AFTER_INSERT, ['backendcomponentsAdminLog', 'write']);
            yiiaseEvent::on(yiidbBaseActiveRecord::className(), yiidbBaseActiveRecord::EVENT_AFTER_UPDATE, ['backendcomponentsAdminLog', 'write']);
            yiiaseEvent::on(yiidbBaseActiveRecord::className(), yiidbBaseActiveRecord::EVENT_AFTER_DELETE, ['backendcomponentsAdminLog', 'write']);
        },

    记录函数

    <?php
    
    namespace backendcomponents;
    
    use Yii;
    use yiihelpersStringHelper;
    use yiihelpersUrl;
    use yiidbActiveRecord;
    
    class AdminLog
    {
        public static function write($event)
        {
            // 排除日志表自身,没有主键的表不记录(没想到怎么记录。。每个表尽量都有主键吧,不一定非是自增id)
            if($event->sender instanceof ackendmodelsAdminLog || !$event->sender->primaryKey()) {
                return;
            }
            // 显示详情有待优化,不过基本功能完整齐全
            if ($event->name == ActiveRecord::EVENT_AFTER_INSERT) {
                $description = "%s新增了表%s %s:%s的%s";
            } elseif($event->name == ActiveRecord::EVENT_AFTER_UPDATE) {
                $description = "%s修改了表%s %s:%s的%s";
            } else {
                $description = "%s删除了表%s %s:%s%s";
            }
            if (!empty($event->changedAttributes)) {
                $desc = '';
                foreach($event->changedAttributes as $name => $value) {
                    if (!is_string($value) and !empty($value)){
                        $value=var_export($value,true);//解决当为数组时的异常问题
                    }
                    $info=$event->sender->getAttribute($name);
                    if (!is_string($info) and !empty($info)){
                        $info=var_export($info,true);
                    }
    
                    $desc .= $name . ' : ' . $value . '=>' . StringHelper::truncate($info,256) . ',';
                }
                $desc = substr($desc, 0, -1);
            } else {
                $desc = '';
            }
            $userName = Yii::$app->user->identity->username;
            $tableName = $event->sender->tableSchema->name;
            $description = sprintf($description, $userName, $tableName, $event->sender->primaryKey()[0], $event->sender->getPrimaryKey(), $desc);
    
            $route = Url::to();
            $userId = Yii::$app->user->id;
            $ip = sprintf('%u',ip2long(Yii::$app->request->userIP));
            $data = [
                'route' => $route,
                'description' => $description,
                'user_id' => $userId,
                'ip' => $ip,
                'created_at' => time(),
            ];
            $model = new ackendmodelsAdminLog();
            $model->setAttributes($data);
            $model->save(false);
        }
    }
  • 相关阅读:
    关于C 语言的字符串常量拼接
    网络处理器简介
    杨先生的博客目录(持续更新......)
    搭建json-server服务
    Spring boot + Mybatis + SQLite 搭建blog API
    使用json-server POST 数据结果只有id
    解决python查询数据库字段为decimal类型的数据结果为科学计数法的问题
    Maven仓库安装配置及使用
    Jekins发送Allure测试报告邮件
    Jenkins发送邮件配置
  • 原文地址:https://www.cnblogs.com/huay/p/12123334.html
Copyright © 2020-2023  润新知