在 Magento2 中写日志文件

为了在 Magento 2 中写入日志,必须强制使用 Monolog 库记录日志,本文,Monolog 的日志类在:MAGENTO_ROOT/vendor/monolog/monolog/src/Monolog/Logger.php 。通过两个步骤想你详细的说明使用方法。

步骤概览

  • 第一步:在你的模块中写入用户日志

  • 第二步:刷新缓存并检查结果

第一步:在你的模块中写入用户日志

在你的模块中,请使用 app/code/Mageplaza/HelloWorld/Block/Post.php 中的一种函数。今天的教程中,我们将会使用到不同类型的日志,例如: info(消息),alert(警告), notice(通知), critical(危险),error(错误),和 debug(调试),这些类型的日志将会归档在 system.log 文件中,debug(调试)类型的日志会被记录在 debug.log 文件中。

<?php
namespace Mageplaza\HelloWorld\Post;
class Post extends \Magento\Framework\View\Element\Template
{
        protected $_logger;
 
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Psr\Log\LoggerInterface $logger,
        array $data = []
    )
    {        
        $this->_logger = $logger;
        parent::__construct($context, $data);
    }
    
    public function testLogging() 
    {    
        // monolog's Logger class
        // MAGENTO_ROOT/vendor/monolog/monolog/src/Monolog/Logger.php
        
        // saved in var/log/debug.log
        $this->_logger->debug('debug1234'); 
        //Output: [2017-02-22 04:48:44] main.DEBUG: debug1234 {"is_exception":false} []
        
        $this->_logger->info('info1234'); 
        // Write to default log file: var/log/system.log
        //Output: [2017-02-22 04:52:56] main.INFO: info1234 [] []
        
        $this->_logger->alert('alert1234'); 
        // Write to default log file: var/log/system.log
        //Output: [2017-02-22 04:52:56] main.ALERT: alert1234 [] []
        
        $this->_logger->notice('notice1234'); 
        // Write to default log file: var/log/system.log
        //Output: [2017-02-22 04:52:56] main.NOTICE: notice1234 [] []
        
        // Write to default log file: var/log/system.log
        $this->_logger->error('error1234'); 
        //Output: [2017-02-22 04:52:56] main.ERROR: error1234 [] []
        
         // Write to default log file: var/log/system.log
        $this->_logger->critical('critical1234'); 
        //Output: [2017-02-22 04:52:56] main.CRITICAL: critical1234 [] []
        
        // Adds a log record at an arbitrary level
        $level = 'DEBUG';
        // saved in var/log/debug.log
        $this->_logger->log($level,'debuglog1234', array('msg'=>'123', 'new' => '456')); 
        //Output: [2017-02-22 04:52:56] main.DEBUG: debuglog1234 {"msg":"123","new":"456","is_exception":false} []
        
        // Write to default log file: var/log/system.log
        $level = 'ERROR';
        $this->_logger->log($level,'errorlog1234', array( array('test1'=>'123', 'test2' => '456'), array('a'=>'b') )); 
        //Output: [2017-02-22 04:52:56] main.ERROR: errorlog1234 [{"test1":"123","test2":"456"},{"a":"b"}] []        
        
    }
    
}
?>

第二步:刷新缓存并检查结果

请刷新缓存并检查结果

如果遇到报错信息:Exception printing is disabled by default for security reasons, 请参考此文章

本教程翻译自Mageplaza模块开发系列,其他内容请点击下面链接: