Analysis of log usage in the Yii2 framework, and yii2 framework
This document describes how to use logs in the Yii2 framework. We will share this with you for your reference. The details are as follows:
Differences between Yii2 and Yii1.x
The log usage in Yii2 is different from that in Yii 1.x,
In Yii 1. x, the method for logging is
Yii::log($message, $level, $category);Yii::trace($message, $category);
The latter only records logs in debug mode.
The log method here is the static method of YiiBase.
In Yii2, the object-oriented design is more thorough, the logging function is transferred to the Logger class, and multiple output Targets (Targets) are supported ).
Log usage in Yii2
To record logs, you first need to obtain a single Logger-type instance and then call the Public logging method of this class:
Yii::getLogger()->log($msg, $level, $category)
Example:
Yii: getLogger ()-> log ("your site has been hacked", Logger: LEVEL_ERROR) // The default category is application-level logs.
In addition, Yii2 provides some shortcuts:
Yii::trace()Used to record logs during development and debugging. You need to set YII_DEBUG to true.
Yii::error()Used to record unrecoverable errors
Yii::warning()Warning Information
Yii::info()Some system behavior records, such as Administrator operation prompt
Yii2 custom log output target
To customize the target, for example, to record files and send emails when an irreparable error occurs, you can customize the following:
[ 'bootstrap' => ['log'], // ensure logger gets loaded before application starts 'components' => [ 'log' => [ 'targets' => [ 'file' => [ 'class' => 'yii\log\FileTarget', 'levels' => ['trace', 'info'], 'categories' => ['yii\*'], ], 'email' => [ 'class' => 'yii\log\EmailTarget', 'levels' => ['error', 'warning'], 'message' => [ 'to' => ['admin@techbrood.com', 'support@techbrood.com'], 'subject' => 'New example.com log message', ], ], ], ], ],]
For more information about logs and debuggers, see the Chinese version of the Yii2 authoritative guide.