最近开发一个新的PHP项目,终于脱离了某框架的魔爪(之前被折磨的不轻),选用了江湖中如雷贯耳的Yii2框架。每个项目代码的运行,日志是必不可少的,在开发中踩了一遍Yii2日志管理的坑,看过很多网上对Yii2日志的配置介绍,今天总结一下Yii2对日志的处理分享给大家。

  1.首先看一下log配置:

 return [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [ //可以配置多个log
[
'class' => 'yii\log\FileTarget', //Yii2处理日志的类
'levels' => ['error', 'warning', 'info'], //设置日志记录的级别
'categories' => ['user'], //自定义日志分类
'maxFileSize' => 1024 * 20, //设置文件大小,以k为单位
'logFile' => '@runtime/../logs/user'.date('Ymd'), //自定义文件路径 (一般项目的日志会打到服务器的其他路径,需要修改相应目录的权限哦~)
'logVars' => ['_POST'], //捕获请求参数
'fileMode' => 0775, //设置日志文件权限
'maxLogFiles' => 100, //同个文件名最大数量
'rotateByCopy' => false, //是否以复制的方式rotate
'prefix' => function() { //日志格式自定义 回调方法
if (Yii::$app === null) {
return '';
}
$request = Yii::$app->getRequest();
$ip = $request instanceof Request ? $request->getUserIP() : '-';
$controller = Yii::$app->controller->id;
$action = Yii::$app->controller->action->id;
return "[$ip][$controller-$action]";
},
],
];

  2.日志记录

    Yii::trace():记录一条消息去跟踪一段代码是怎样运行的。这主要在开发的时候使用。 
    Yii::info():记录一条消息来传达一些有用的信息。 
    Yii::warning():记录一个警告消息用来指示一些已经发生的意外。 
    Yii::error():记录一个致命的错误,这个错误应该尽快被检查。

    eg: Yii::info('the log content', 'user');

      第二个参数可以是自定义的日志分类,对应配置文件中categories字段。

  3.日志组件调用

    log配置通过web.php(基础模板web.php 高级模板main.php)以component方式加载到应用对象Yii::$app中。

  4.日志切分

    ./vendor/yiisoft/yii2/log/FileTarget.php

 class FileTarget extends Target
{
public $logFile;
//rotation开关 如果开启,当日志文件大于maxFileSize设定的文件大小之后,就会自动切分日志
public $enableRotation = true;
public $maxFileSize = 10240; // in KB
//同一个文件名可以切分多少个文件
public $maxLogFiles = 5;
public $fileMode; //日志文件权限
public $dirMode = 0775;
/**
* @var bool Whether to rotate log files by copy and truncate in contrast to rotation by
* renaming files. Defaults to `true` to be more compatible with log tailers and is windows
* systems which do not play well with rename on open files. Rotation by renaming however is
* a bit faster.
*
* The problem with windows systems where the [rename()](http://www.php.net/manual/en/function.rename.php)
* function does not work with files that are opened by some process is described in a
* [comment by Martin Pelletier](http://www.php.net/manual/en/function.rename.php#102274) in
* the PHP documentation. By setting rotateByCopy to `true` you can work
* around this problem.
*/
public $rotateByCopy = true; /**
* Rotates log files.
*/
protected function rotateFiles()
{
$file = $this->logFile;
for ($i = $this->maxLogFiles; $i >= 0; --$i) {
// $i == 0 is the original log file
$rotateFile = $file . ($i === 0 ? '' : '.' . $i);
if (is_file($rotateFile)) {
// suppress errors because it's possible multiple processes enter into this section
if ($i === $this->maxLogFiles) {
@unlink($rotateFile);
} else {
if ($this->rotateByCopy) {
@copy($rotateFile, $file . '.' . ($i + 1));
if ($fp = @fopen($rotateFile, 'a')) {
@ftruncate($fp, 0);
@fclose($fp);
}
if ($this->fileMode !== null) {
@chmod($file . '.' . ($i + 1), $this->fileMode);
}
} else {
// linux下用rename方式
@rename($rotateFile, $file . '.' . ($i + 1));
}
}
}
}
}
}

  5.日志前缀

    prefix:如果没有配置,默认调用./vendor/yiisoft/yii2/log/Target.php

 public function getMessagePrefix($message)
{
if ($this->prefix !== null) {
return call_user_func($this->prefix, $message);
} if (Yii::$app === null) {
return '';
} $request = Yii::$app->getRequest();
$ip = $request instanceof Request ? $request->getUserIP() : '-'; /* @var $user \yii\web\User */
$user = Yii::$app->has('user', true) ? Yii::$app->get('user') : null;
if ($user && ($identity = $user->getIdentity(false))) {
$userID = $identity->getId();
} else {
$userID = '-';
} /* @var $session \yii\web\Session */
$session = Yii::$app->has('session', true) ? Yii::$app->get('session') : null;
$sessionID = $session && $session->getIsActive() ? $session->getId() : '-'; return "[$ip][$userID][$sessionID]";
}

    如果想要自定义日志格式前缀,可以配置回调函数(note:如果在回调中使用了特定的类需要在文件开头用“use”关键词 引入该类)

Yii2 日志处理的更多相关文章

  1. 我 && yii2(日志埋点,邮件提醒)

    今天试着把yii2 的日志,如果发送邮件的形式实现,具体实现如下 1.环境介绍 lnmp php5.6, mysql5.5, lnmp1.2 yii2-advanced 2.配置文件的编写 在fron ...

  2. YII2 日志

    YII 提供的日志写入方法: Yii::getLogger()->log($message, $level, $category = 'application') Yii::trace($mes ...

  3. yii2 日志(log)的配置与使用

    原文地址: http://blog.csdn.net/gao_yu_long/article/details/51732181

  4. Yii日志使用

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

  5. yii2-CaptchaAction macos500 不显示

    把公司一个项目pull到本地 发现验证码不输出了 怀疑是gd库没装  php -m看了下 gd库是装了的 有搜索到可能是因为自带的php拓展生成不了png(觉得不太可能) 试了下自己写一个图片生成pn ...

  6. Yii2 中日志的记录

    Yii2自带日志记录,但用起来感觉比较不是很顺手,故自己封装了个方法,如下: /** * 记录日志 * * @param type $msg * @time 2015年8月31日17:46:20 * ...

  7. Yii2 捕获错误日志

    在技术开发中,捕获程序框架错误,是非常必要的一件事情,我们公司使用Yii2框架,简单说下Yii2的错误捕获处理 Yii2 web应用 1 配置如下 其中errorHandler就是错误处理配置,执行E ...

  8. Yii2如何添加sql日志记录的配置信息

    在使用Yii2框架的时候,常常会出现没有sql日志记录的问题.在代码里一句一句的打印sql语句也不现实.所以就要用文件记录起来. 在 config/web.php 里面的 log配置中增加如下配置 [ ...

  9. YII2中日志的配置与使用

    YII2中给我们提供了非常方便的日志组件,只需要简单配置一下就可以使用. 我们在config/web.php中配置如下: return [ //log必须在bootstrap期间就被加载,便于及时调度 ...

随机推荐

  1. winform打开本地html页面

    有时候为了提高开发效率和后期可维护性,把cs里面嵌套了远程网页,这样方便后期升级.比如,美图秀秀,qq音乐PC都嵌套了本地和远程网页.在页面拖入控件System.Windows.Forms.WebBr ...

  2. TemplateMethod-模板模式

    什么是Template Method模式 在父类中定义处理流程的框架,在子类中实现具体处理的模式就称为Template Mehtod模式.模板模式的关键是:子类可以置换掉父类的可变部分,但是子类却不可 ...

  3. Linux网络设备驱动架构

    Linux网络设备驱动程序体系结构分为四层:网络协议接口层.网络设备接口层.提供实际功能的设备驱动层以及网络设备与媒介层. (1)网络协议接口层向网络层协议提供统一的数据包收发接口,不论上层协议是AR ...

  4. CSS深入理解学习笔记之absolute

    1.absolute和float 拥有相同的特性表现: ①包裹性(容器应用之后,可以包裹里面的内容): <!doctype html> <html> <head> ...

  5. 译-BSA NSH Command介绍

    BSA NSH Command全称BMC BladeLogic Network Shell Command,是基于ZSH的shell. 1 说明 NSH命令行(全称Network  Shell,又称为 ...

  6. 使用SoapUI调用Vsphere Web Service

    项目中经常需要调用Webservice进行验证测试,下面就介绍下如何使用测试工具SoapUI调用Vsphere vcenter的 Web Service VSphere的Webservice地址默认为 ...

  7. 将centos_yum源更换为阿里云(官方文档)

    http://mirrors.aliyun.com/help/centos?spm=5176.bbsr150321.0.0.d6ykiD 1.备份 mv /etc/yum.repos.d/CentOS ...

  8. SpringMVC解决跨域问题

    有个朋友在写扇贝插件的时候遇到了跨域问题. 于是我对解决跨域问题的方式进行了一番探讨. 问题 API:查询单词 URL: https://api.shanbay.com/bdc/search/?wor ...

  9. AppScan扫描结果分析及工具栏使用

    Appscan的窗口大概分三个模块,Application Links(应用链接), Security Issues(安全问题), and Analysis(分析) Application Links ...

  10. JAVA泛型使用方法总结

    1. 基本概念: (1)什么是泛型? 泛型,即"参数化类型".即将类型由原来的具体的类型参数化,类似于方法中的变量参数,此时类型也定义成参数形式(可以称之为类型形参),然后在使用或 ...