magento2 添加日志 打印日志到system.log

Logs in Magento 2 consist of system information records for the analysis in the future. One of the most common examples of such events is the error log.

Developers know the pain of errors and the process to deliver a working solution. Debugging can be made easier for them by custom logs. It helps to spot an error and the reason for it, easily. Logs contribute to the visibility into Magento 2 system processes.

Now if you want to learn how to print log in Magento 2, you’re at the right place! I have come up with 3 different methods to print log in Magento 2.

  1. Using Helper Data
  2. Using Logger Interface
  3. Using Object Manager

Follow any of the below methods to create your own custom log files and get to solve the errors 🙂

Note:

  1. Make sure that the debug mode is enabled in the backend. Go to Stores -> Configuration -> Advanced -> Developer -> Debug and set “Yes” to Log to File.
  2. Make sure your Magento store is in developer mode.
  3. For production mode, you have to run the below command in shell:
bin/magento config:set dev/debug/debug_logging 1

Methods to Print Log in Magento 2:

Method: 1 Using Helper Data

create file [Vendor][Module]\Helper\Data.php

<?php
namespace [Vendor]\[Module]\Helper;
use Zend\Log\Writer\Stream;
use Zend\Log\Logger;
class Data extends AbstractHelper
{
 public function printLog($log)
 {
       $writer = new Stream(BP . '/var/log/fileName.log');
       $logger = new Logger();
       $logger->addWriter($writer);
       $logger->info($log);
 }
}

Simply call Helper class method where you want to print the log :
create file [Vendor][Module][Path][fileName.php]

<?php
namespace [Vendor]\[Module]\[Path];
use [Vendor]\[Module]\Helper\Data;
protected $helper;
class FileName
{
    public function __construct(Data $helperName)
    {
        $this->helper = $helperName;
    }
    $this->helper->printLog('msg for print');
}
Method 2: Using Logger Interface

To enable the log in custom extension, go to app\code[Vendor][Module][Path][fileName.php] and add below code.

<?php
namespace [Vendor]\[Module]\[Path];
use Psr\Log\LoggerInterface;
class FileName
{
    protected $logger;
    public function __construct(LoggerInterface $logger;)
    {
        $this->logger = $logger;
    }
    $this->logger->debug('msg to print'); // print var\log\debug.log
    $this->logger->info('msg to print');  // print var\log\system.log
}
Method 3: Using ObjectManager

To print the message in var\log\system.log

\Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->info('msg to print');
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容