Magento 2 控制台记录(logging)

2,821 人次阅读
没有评论

共计 2644 个字符,预计需要花费 7 分钟才能阅读完成。

Magento 2 控制台记录(logging)

每次开发过程中,你都会想记录一些一些变量或者用户信息,现在我们就来谈谈怎么创建自定义记录。Magento 2 内建了一个记录模块,是基于Monolog库。可以在下面路径找到: “MAGENTO2_ROOT/vendor/monolog“.

在Magento 2 中,Monolog的类(class)是“Magento\Framework\Logger\Monolog“, 在“MAGENTO2_ROOT/app/etc/di.xml”有这样的定义:

[php]
<preference for="Psr\Log\LoggerInterface" type="Magento\Framework\Logger\Monolog" />[/php]

你可以在monolog包中看到“Monolog\Logger”这个类的扩展类。

[php]
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/

namespace Magento\Framework\Logger;

use Monolog\Logger;

class Monolog extends Logger
{
}
[/php]

在“Monolog\Logger” 类中,有很多种方法可以创建记录(logs)。这些方法中提供两种路径,即Message(string)和 optional array parameter (you can pass instance of object).

方法举例:

[php]
$this->_logger->addDebug($message); // log location: var/log/system.log
$this->_logger->addInfo($message); // log location: var/log/exception.log
$this->_logger->addNotice($message); // log location: var/log/exception.log
$this->_logger->addError($message); // log location: var/log/exception.log
$this->_logger->critical($e); // log location: var/log/exception.log
[/php]

一个很有参考意义的记录php exception的例子:

Magento 1中用静态方法:

[php]
Mage::logException($e);
[/php]

Magento 2 中使用“Magento\Framework\Logger\Monolog”方法和“critical” 来记录 try-catch的exception

[php]
$this->_logger->critical($e);
// instance of $e will be converted to string (magic metod __toString() will be called).[/php]

我们试试从使用你的类获取 Magento\Framework\Logger\Monolog实例开始.

如果你要是用“Magento\Framework\Logger\Monolog”对象,下面是一个案例:

[php]
<?php
namespace Inchoo\Test\Model;

class Example{
protected $_logger;
public function __construct(
\Psr\Log\LoggerInterface $logger, //log injection
array $data = []
) {
$this->_logger = $logger;
parent::__construct($data);
}
public function someExampleMethod() {
/*
some logic of method
*/
//accessing to logger instance and calling log method
$this->_logger->addDebug(‘some text or variable’);
}
}[/php]

这个类从始至终使用“\Psr\Log\LoggerInterface $logger”来传递信息,这样我就可以在类“Inchoo\Test\Model\Example“中使用实例“$this->_logger”。

如果你想在自定义的文件或者位置中写入log,就没有这么容易了。你需要自己创建一个Log handler

Magento 2 已经在 “MAGENTO2_ROOT/app/etc/di.xml”中定义了3个主要的log class handler。这几个Handler分别是 : exception, system and debug.

[php]
<type name="Magento\Framework\Logger\Monolog">
<arguments>
<argument name="name" xsi:type="string">main</argument>
<argument name="handlers" xsi:type="array">
<item name="exception" xsi:type="object">Magento\Framework\Logger\Handler\Critical</item>
<item name="system" xsi:type="object">Magento\Framework\Logger\Handler\System</item>
<item name="debug" xsi:type="object">Magento\Framework\Logger\Handler\Debug</item>
</argument>
</arguments>
</type>[/php]

有时候log object已经存在框架中了,我们就没有比较再在框架中传递log object了。
例如,我们在每个html block中都会碰到的情况:在“\Magento\Framework\View\Element\Template” 或者 “\Magento\Framework\Model\AbstractModel“.

父类中已经有了 $_logger” : Magento\Framework\Logger.

希望这个文章能对你有用!

正文完
 0