Common log operations of Yii framework in PHP

不言
Release: 2023-04-01 13:50:01
Original
1841 people have browsed it

This article mainly introduces a summary of common log operations of PHP's Yii framework, including basic content such as message skipping and formatting. Friends in need can refer to it

Log
Yii provides a highly customizable and extensible logging framework. Depending on the usage scenario, you can easily record, filter, and merge various messages, such as text files, database files, and emails.

Using Yii's logging framework includes the following steps:

Call the logging method

  • In the main application Configure the log filtering and export settings in the configuration file (such as web.php under basic)

  • Check the filtered log information in different scenarios

  • Logging

Logging is actually simply calling the following method:

  • [[Yii:: trace()]]: Record relevant messages about the execution of a certain piece of code. Mainly used in development environment.

  • [[Yii::info()]]: Used when recording some useful information in certain locations.

  • [[Yii::warning()]]: Use this method when something unexpected happens.

  • [[Yii::error()]]: When some fatal problems that need to be solved immediately occur, call this method to record relevant information.

Although the above methods record information according to different levels and types, they actually call the same method function($message, $category = 'application'). Among them, $message is the information to be recorded, and $category indicates the category of this log. The following code indicates that a trace type information is recorded under the default 'application' category.

 Yii::trace('start calculating average revenue');
Copy after login

Tip: The recorded $message can be a simple string or a complex array or object. You should select the appropriate $message type based on logging responsibilities in different scenarios. By default, if the $message you record is not a String, the [[yii\helpers\VarDumper::export()]] method will be called when exporting the log to output a string type message.

In order to better organize, manage and filter log messages, usually each type of log should be assigned an appropriate category. You can choose a category with obvious hierarchical meaning to facilitate filtering logs of different categories according to different purposes. A simple and effective naming method is to use PHP's magic constant METHOD as the name of the category. This is what the core code in the Yii framework does when doing logging. For example:

Yii::trace('start calculating average revenue', __METHOD__);
Copy after login

Wherever the constant METHOD appears, it represents the name of the current method (plus the complete prefix of the class to which the current method belongs). For example, if there is the above line of code in the calculate method in the app\controllers\RevenueController class, then the METHOD at this time represents 'app\controllers\RevenueController::calculate'.

Tip: The above method is actually just [[yii\log\Logger::log()|log()]] of the singleton object [[yii\log\Logger|logger object]] Simple use of the method, we can obtain this singleton object through the Yii::getLogger() method. When we have recorded enough log information or the current application has ended, the log object will call the [yii\log\Dispatcher|message dispatcher]] method to write the recorded log information to the configured destination.

log targets
A log target is an instance of [[yii\log\Target]] or its subclass. It filters logs based on severity level and classification, and then exports the logs to appropriate media. For example, a [[yii\log\DbTarget|database target]] object will export the filtered log information to the corresponding database.
You can register multiple log targets at the log component in the application configuration file, as follows:

return [
// the "log" component must be loaded during bootstrapping time
'bootstrap' => ['log'],

'components' => [
  'log' => [
    'targets' => [
      [
        'class' => 'yii\log\DbTarget',
        'levels' => ['error', 'warning'],
      ],
      [
        'class' => 'yii\log\EmailTarget',
        'levels' => ['error'],
        'categories' => ['yii\db\*'],
        'message' => [
          'from' => ['log@example.com'],
          'to' => ['admin@example.com', 'developer@example.com'],
          'subject' => 'Database errors at example.com',
        ],
      ],
    ],
  ],
],
];
Copy after login

Note: The log component must be configured in bootstrap so that the log information can be distributed to The corresponding log target.
In the above code, two log targets are registered in [[yii\log\Dispatcher::targets]].

The first one filters out error and warning information and saves this information to the database.
The second one filters out error messages whose categories begin with yii\db* and sends these messages to admin@example.com and developer@example.com via email.
Yii has the following built-in log targets , you can refer to the API documentation to learn how to configure and use them.

  • [[yii\log\DbTarget]]: Save log information to the database.

  • [[yii\log\EmailTarget]]: Send log information to the specified mailbox, as in the above example.

  • [[yii\log\FileTarget]]: Write the log to the file.

  • [[yii\log\SyslogTarget]]: Call PHP's syslog() method to write the log to the system log.

Next, let’s take a look at the functions of common log targets.

消息过滤
就每一种log target而言,你可以配置它的 [[yii\log\Target::levels|levels]] 和 [[yii\log\Target::categories|categories]]属性类设置它的严重程度以及归属的分类。
[[yii\log\Target::levels|levels]]属性的采用一个数组里面的一个或者多个值,这个数组包含如下值:

  • error:对应[[Yii::error()]]记录的消息

  • warning:对应[[Yii::warning()]]记录的消息

  • info :对应 [[Yii::info()]]记录的信息

  • trace:对应 [[Yii::trace()]]记录的信息.

  • profile :对应[[Yii::beginProfile()]] 和 [[Yii::endProfile()]]记录的信息,这种方式下面更多详细信息会被记录。

如果你没有指定[[yii\log\Target::levels|levels]] 的值,那么任何level的信息都会被记录。

[[yii\log\Target::categories|categories]] 属性的值是数组,这个数组里面的值可以是一个具体的分类名称,也可以是类似正则的匹配模式。只有在target能在这个数组里面找到对应的分类名或者符合某一个匹配模式,他才会处理这些消息。这里的匹配模式的组成是在分类的名称后面加上一个号。如果这个分类恰好和这个匹配模式的号前的字符匹配,那么也就是这个分类找到对应匹配值。举个例来说,在类[[yii\db\Command]]中的yii\db\Command::execute和yii \db\Command:: query 方法使用类名类记录相关日志信息,那么这个时候他们都匹配模式yii\db*

同样的,如果我们没有指定[[yii\log\Target::categories|categories]],那么每一种分类的日志信息都会被处理。
除了通过[[yii\log\Target::categories|categories]] 属性来设置分类的白名单外,你也可以通过 [[yii\log\Target::except|except]]属性来设置分类的黑名单。属于黑名单的分类日志信息不会被target处理。

下面的配置指定了一个分类匹配yii\db*或者 yii\web\HttpException:*,但又不包括yii\web\HttpException:404的分类,而且它只处理错误和警告的日志信息。

[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
'categories' => [
  'yii\db\*',
  'yii\web\HttpException:*',
],
'except' => [
  'yii\web\HttpException:404',
],
]
Copy after login

注意:当错误的句柄捕获到HTTP的异常的时候,记录的日志信息会以yii\web\HttpException:ErrorCode的这种格式
记录,例如[[yii\web\NotFoundHttpException]] 就会被记录成yii\web\HttpException:404
消息格式化
日志targets用多种格式来导出日志。举个例子,如果你的日志target是[[yii\log\FileTarget]],那么你在你的程序中记录日志的时候,应该会找到类似于文件runtime/log/app.log 记录的如下的信息:

2014-10-04 18:10:15 [::1][][-][trace][yii\base\Module::getModule] Loading module: debug
Copy after login

默认情况下,[[yii\log\Target::formatMessage()]]:会帮我们把日志信息格式化成下面的这种格式:

Timestamp [IP address][User ID][Session ID][Severity Level][Category] Message Text
Copy after login

你可以通过给[[yii\log\Target::prefix]] 属性配置一个自定义的回调函数来 自定义日志的前缀。下面的代码就实现了在每条日志信息前面加上了用户的ID(ip地址,sessionId等敏感信息因为个人隐私被去掉了)。

[
'class' => 'yii\log\FileTarget',
'prefix' => function ($message) {
  $user = Yii::$app->has('user', true) ? Yii::$app->get('user') : null;
  $userID = $user ? $user->getId(false) : '-';
  return "[$userID]";
}
]
Copy after login

除了日志消息的前缀,日志的target还把一些上下文信息附加在了每一批的日志记录中。默认情况下,全局的PHP变量包含$_GET, $_POST, $_FILES, $_COOKIE, $_SESSION 和 $_SERVER. 你可以通过配置 [[yii\log\Target::logVars]] 来调整日志记录的全局变量。下面的代码表示的是只记录$_SERVER相关的变量。

[
'class' => 'yii\log\FileTarget',
'logVars' => ['_SERVER'],
]
Copy after login

当 'logVars'为空的时候,表示不记录相关的上下文信息。如果你想自定义上下文信息的提供方式,你可以覆写[[yii\log\Target::getContextMessage()]] 方法。

消息的trace等级
在开发的过程当中,我们总是期望能够知道每一条日志消息是来自哪里。在Yii中你可以通过配置[[yii\log\Dispatcher::traceLevel|traceLevel]] 属性来实现。配置的示例如下:

return [
'bootstrap' => ['log'],
'components' => [
  'log' => [
    'traceLevel' => YII_DEBUG ? 3 : 0,
    'targets' => [...],
  ],
],
];
Copy after login

上面的示例在YII_DEBUG为true的时候将[[yii\log\Dispatcher::traceLevel|traceLevel]] 设置为3,反之设置为0. 意思是什么呢?3表示每一条日志记录都会记录与之相关的三层栈调用信息,0表示不记录任何相关的栈调用信息

提示:没有必要总是记录调用的堆栈信息,比较耗性能。所以,你应该只在你开发的时候或者用于调试的情况下使用该功能。
消息的清空和导出
就如同上面说的,记录的消息以数组的形式保存在[[yii\log\Logger|logger object]]中。为了限制这个数组消耗过多的内存,当这个数组包含的内容大小达到某个量的时候会被对应的target从内存中转移到对应的目标(文件,数据库...)中。你可以通过设置 [[yii\log\Dispatcher::flushInterval|flushInterval]] 的值来决定量的大小。像下面这样:

return [
'bootstrap' => ['log'],
'components' => [
  'log' => [
    'flushInterval' => 100,  // default is 1000
    'targets' => [...],
  ],
],
];
Copy after login

注意:在应用运行结束的时候也会刷新内存,这样做事为了让日志的target能够记录完整的信息。
把日志信息从内存刷到对应存放的地方的这一动作不是立即发生的。事实上,和上面一样,都是当内存中的日志大小达到一定程度才会发生。你可以像下面的示例一样通过配置不同target的[[yii\log\Target::exportInterval|exportInterval]]值,来达到修改的目的:

[
'class' => 'yii\log\FileTarget',
'exportInterval' => 100, // default is 1000
]
Copy after login

因为清空和导出的设定,默认情况下你调用 Yii::trace() 或者其他的日志记录方法的时候不会在日志target下立马看到日志消息。这对某些长时间运行的控制台程序是一个问题。不过这个问题是可以解决的,方法入下面的代码,你需要把[[yii\log\Dispatcher::flushInterval|flushInterval]] 和[[yii\log\Target::exportInterval|exportInterval]] 的值都设置成1:

return [
'bootstrap' => ['log'],
'components' => [
  'log' => [
    'flushInterval' => 1,
    'targets' => [
      [
        'class' => 'yii\log\FileTarget',
        'exportInterval' => 1,
      ],
    ],
  ],
],
];
Copy after login

注意:如此频繁的清空和导出日志消息会降低系统的性能。

切换日志的targets
你可以通过设置[[yii\log\Target::enabled|enabled]] 属性来禁止日志的target。就如同下面的代码描述的一样:

Yii::$app->log->targets['file']->enabled = false;
Copy after login

上面的代码需要你在配置文件里面有一个下面的配置:

return [
'bootstrap' => ['log'],
'components' => [
  'log' => [
    'targets' => [
      'file' => [
        'class' => 'yii\log\FileTarget',
      ],
      'db' => [
        'class' => 'yii\log\DbTarget',
      ],
    ],
  ],
],
];
Copy after login

创建一个新的target
首先,创建一个新的日志target是很简单的。你主要做的事情是实现[[yii\log\Target::export()]] 方法并且把数组类型的消息[[yii\log\Target::messages]]发送到指定的存储媒介上去就行了。在这个过程中你可以调用[[yii\log\Target::formatMessage()]] 方法来格式化每一条日志消息。至于更多的细节你可以在Yiid的发行版本里找到详细的信息。

性能评测
性能评测是一种比较特别的日志记录。它通常用来获取某些模块执行时间的数据,以此来找到性能的问题所在。比如说,[[yii\db\Command]] 这个类就用性能评测日志来获得每一条sql查询所花费的时间。

要使用该类日志,你首先要做的时确定你要测试的代码范围。然后在每一段代码之间你都应该要保持它们是闭合的,就像下面这个样子:

\Yii::beginProfile('myBenchmark');
...code block being profiled...
\Yii::endProfile('myBenchmark');
Copy after login

myBenchmark只是一个标识,用于你在查看对应日志记录的时候快速定位。
在beginProfile和endProfile之间是可以再嵌套的,但是必须保证正确的闭合关系,如下所示:

\Yii::beginProfile('block1');

// some code to be profiled

\Yii::beginProfile('block2');
  // some other code to be profiled
\Yii::endProfile('block2');

\Yii::endProfile('block1');
Copy after login

如果上面的闭合关系出错了,对应的记录都不会正常工作。

对于每一块被评测的代码,日志的level都是profile。你可以再日志的target中配置这些信息并导出它们。 Yii内建了 Yii debugger来展示评测的结果。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

关于PHP的Yii框架中的日志功能

The above is the detailed content of Common log operations of Yii framework in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template