日志

配置

'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. 六、Django学习之基于下划线的跨表查询

    六.Django学习之基于下划线的跨表查询 一对一 正向查询的例子为 已知用户名,查询用户的电话号码.反向查询例子反之. 正向查询 其中下划线前的表示表名,无下划线的表示的是Author表 resul ...

  2. C#系列之基础知识点(一)

    知识点一:VS启动方法 第一种:双击图标 第二种:window+R——调出cmd,输入devenu properties  属性的意思 知识点二:后缀名解释 .sln  解决方案文件:包含整个解决方案 ...

  3. Golang设置https访问,以及http如何重定向到https

    设置https访问: 原始代码为http监听: func main() { server := &http.Server{ Addr: ":8080", ... } go ...

  4. create-react-app 打包后静态文件过大 webpack优化

    在最近的项目里,页面和静态文件并不是很多的情况下,打包后发现产出的静态资源却很大. 1.关掉sourcemap 在config/webpack.config.js文件里,大概30几行的位置添加这样一句 ...

  5. linux shell 操作 mysql命令(不进入mysql操作界面)

    由于需要,需要将一系列mysql的操作制作成.sh文件,只需要shell操作bash命令就可以傻瓜式的完成黑盒任务. #!/bin/bash mysql -uroot -p??? -e "c ...

  6. kubernetes(14):k8s基于NFS部署storageclass实现pv自动供给

    k8s基于NFS部署storageclass实现pv自动供给 https://www.cnblogs.com/Smbands/p/11059843.html https://www.jianshu.c ...

  7. python图片处理PIL

    一.PIL介绍 PIL中所涉及的基本概念有如下几个:通道(bands).模式(mode).尺寸(size).坐标系统(coordinate system).调色板(palette).信息(info)和 ...

  8. FastDFS 配置文件 client.conf storage_ids.conf

    client.conf : # connect timeout in seconds # default value is 30s connect_timeout=30              连接 ...

  9. [Redis-CentOS7]Redis打开远程连接(十) Could not connect to Redis at 127.0.0.1:6379: Connection refused

    通过网络无法访问Redis redis-cli 172.16.1.111 Could not connect to Redis at 127.0.0.1:6379: Connection refuse ...

  10. rhel6.5安装网络yum源过程

    **redhat的yum在线更新是收费的,如果没有注册的话不能使用,如果要使用,需将redhat的yum卸载后,重启安装其他yum源,再配置其他源.** 本文包括配置本地源及第三方源.第三方源包括:网 ...