日志

配置

'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
], //以文件的方式记录
[
'class' => 'yii\log\FileTarget',
'levels' => ['info'],
'categories' => ['shopify'],
'logVars' => ['*'],//不记录PHP全局变量$_POST等
'logFile' => '@runtime/logs/shopify.log',
// 'exportInterval' => 1,//在导出消息之前应该累积多少条消息
'maxFileSize' => 1024 * 2,//文件大小
'maxLogFiles' => 20,
], //以邮件的方式记录,这种方式后面还需设置邮箱的账号密码和host
[
'class' => 'yii\log\EmailTarget',
'levels' => ['info'],
'categories' => ['shopify'],
'logVars' => ['*'],//不记录PHP全局变量$_POST等
'message' => [
'from' => ['service@hjk.top'],
'to' => ['yowwoy@hjk.com'],
'subject' => '商城预警',
],
],
],
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'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) {
\yii\base\Event::on(\yii\db\BaseActiveRecord::className(), \yii\db\BaseActiveRecord::EVENT_AFTER_INSERT, ['backend\components\AdminLog', 'write']);
\yii\base\Event::on(\yii\db\BaseActiveRecord::className(), \yii\db\BaseActiveRecord::EVENT_AFTER_UPDATE, ['backend\components\AdminLog', 'write']);
\yii\base\Event::on(\yii\db\BaseActiveRecord::className(), \yii\db\BaseActiveRecord::EVENT_AFTER_DELETE, ['backend\components\AdminLog', 'write']);
},

记录函数

<?php

namespace backend\components;

use Yii;
use yii\helpers\StringHelper;
use yii\helpers\Url;
use yii\db\ActiveRecord; class AdminLog
{
public static function write($event)
{
// 排除日志表自身,没有主键的表不记录(没想到怎么记录。。每个表尽量都有主键吧,不一定非是自增id)
if($event->sender instanceof \backend\models\AdminLog || !$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 \backend\models\AdminLog();
$model->setAttributes($data);
$model->save(false);
}
}

yii 日志和事件的更多相关文章

  1. YII框架的事件机制

    一.什么是事件机制 解释:发生了一件事情,然后某些东西对这件事作出反应. 例子:假设发生了A同学结婚事件,然后B同学给份子钱反应,那么,B是怎么知道(监听)A事件的发生了呢,有两种办法. 扫描式:B不 ...

  2. yii日志保存机制

    一.修改yii框架的配置文件(main.php) 'log' => array( 'class' => 'CLogRouter', 'routes' => array( array( ...

  3. Yii日志记录Logging

    .Yii::getLogger()->log($message, $level, $category = 'application') .Yii::trace($message, $catego ...

  4. 干货:yii日志功能详解

    转载请注明来自souldak,微博:@evagle 一.基本日志功能 详细的介绍查看官网的document:http://www.yiiframework.com/doc/guide/1.1/en/t ...

  5. Yii日志使用

    Yii 提供了一个灵活可扩展的日志功能.记录的日志 可以通过日志级别和信息分类进行归类.通过使用 级别和分类过滤器,所选的信息还可以进一步路由到 不同的目的地,例如一个文件,Email,浏览器窗口等. ...

  6. Yii 日志组件

    详细的介绍查看官网的document:http://www.yiiframework.com/doc/guide/1.1/en/topics.logging 也可以看 Yii 1.1 Applicat ...

  7. 使用EventLog类写Windows事件日志

    在程序中经常需要将指定的信息(包括异常信息和正常处理信息)写到日志中.在C#3.0中可以使用EventLog类将各种信息直接写入Windows日志.EventLog类在System.Diagnosti ...

  8. EventLog组件读写事件日志

    使用.Net中的EventLog控件使您可以访问或自定义Windows 事件日志,事件日志记录关于重要的软件或硬件事件的信息.通过 EventLog,可以读取现有日志,向日志中写入项,创建或删除事件源 ...

  9. .NET 操作 EventLog(Windows事件日志监控)(转载)

    操作Windows日志:EventLog 如果要在.NET Core控制台项目中使用EventLog(Windows事件日志监控),首先需要下载Nuget包: System.Diagnostics.E ...

随机推荐

  1. 表达式属性(C#6.0和C#7.0

    从C#6开始,只读属性可简写为表达式属性.它使用双箭头替换了花括号,get访问器和return关键字. 例如: decimal CurrentPrice,sharedOwned; public dec ...

  2. QT5如何设置QLabel中字体的颜色

    修改了wd的文章: 如何使用Qt5,设置QLabel中字体的颜色. 大致有几种做法: 一是使用setPalette()方法: 二是使用样式表: 三是可以使用QStyle: 四是可以在其中使用一些简单的 ...

  3. C语言宏的神奇写法:语句块作为参数,算半个函数式编程?

    我想要写几个循环做测试代码,每次都写 `for(size_t i = 0; i < n; i++)` 很烦人,然后就灵机一动,能不能用宏实现,然后就写出了: #define repeat(n, ...

  4. TensorFlow 中的张量,图,会话

    tensor的含义是张量,张量是什么,听起来很高深的样子,其实我们对于张量一点都不陌生,因为像标量,向量,矩阵这些都可以被认为是特殊的张量.如下图所示: 在TensorFlow中,tensor实际上就 ...

  5. BZOJ 4556(后缀数组+主席树求前驱后继+二分||后缀数组+二分+可持久化线段树)

    换markdown写了.. 题意: 给你一个1e5的字符串,1e5组询问,求\([l_1,r_1]\)的所有子串与\([l_2,r_2]\)的lcp 思路: 首先可以发现答案是具有单调性的,我们考虑二 ...

  6. 2018icpc南京网络赛-L Magical Girl Haze (分层图最短路)

    题意: 有向图,可以把k条路的长度变为0,求1到n的最短路 思路: 将图复制k份,一共k+1层图,对于每一条i→j,都连一条低层的i→高层的j,并且权值为0 即对每一对<i,j,w>,都加 ...

  7. Pycharm学习记录---同一目录下无法import明明已经存在的.py文件

    转自:https://blog.csdn.net/l8947943/article/details/79874180 问题描述: 如图:同目录下明明存在相应文件,在导入时却出现带有红色波浪线,说没有相 ...

  8. Java并发编程-扩展可回调的Future

    前提 最近在看JUC线程池java.util.concurrent.ThreadPoolExecutor的源码实现,其中了解到java.util.concurrent.Future的实现原理.从目前j ...

  9. coroutine - yield from

    yield from yield from x 表达式对 x 对象所做的第一件事是,调用 iter(x),从中获取迭代器.因 此, x 可以是任何可迭代的对象. 可是,如果 yield from 结构 ...

  10. vue 信使 ------fetch、axios

    fetch 1.什么是fetch 相当于promise 必须写两个then 第一个then返回状态码 返回成json格式 第二个then返回json数据 2.使用方法 $ npm install fe ...