Magento Logger: The best way to understand your application and make better decisions for it

Nowadays, each platform has its own set of features and advantages. Especially, a big E-commerce platform that completes every need of an e-commerce store, however, Magento will give you more detailed instructions. To help users identify and categorize errors, the Magento log feature maintains errors and exceptions logs for your e-commerce store. In this article, we will show you the manual knowledge of Magento 2 Logger, and the methods to write the logs.

What is Magento Logger?

Magento Logger

magento logger

When a visitor archives a request, it is originally handled by the server (Apache).  Magento sends the inquiry to the database (MySQL). While following this flow, there are chances of errors. That’s a cause of the Magento logger maintaining a complete log of all the activities to help with error identification and resolution.

Ways To View Magento  Logger

There are 4 ways to view the Magento Logs: Log Directories, Via FTP structure, Via CLI, Project web UI. 

Log Directories

All Magento logs are maintained in the var/log directory which can be approached via SSH/CLI or FTP with default.

Via FTP structure

To view a detailed Magento log, please download it on a local drive.

/applications/[application folder]/public_html/var/log

magento logger

Via CLI

Use the below command to access the Magento 2 logger file:

cd public_html/var/log

magento

 Use the following command to view the Magento log file once you get into the folder.

ls -l

magento logger

Project web UI

You can see build and post-deploy log information in the environment messages list.

Project web UI

You can see build and post-deploy log information in the environment messages list.

Magento Logger Type and Detail Information

What is Magento PHP Logs?

Magento PHP built-in error logs usually show information associated:

  • Failing a core function or code determining
  • PHP custom errors triggered in the application 
  • All activities performed in the Magento application may be helpful in the analysis of some problem

When log_errors are enabled but are not correctly determined, these Magento errors are logged in the web server error log which is maintained in the Apache and NGINX logs.

Magento PHP Logging Functions

Magento uses core PHP error functions to report errors.

error_log()

The most common core is:

error_log(‘Your message’);

An Apache server will show the error like this:

[20-Jul-2020 18:20:02 Europe/Malta] Your message

trigger_error()

This function is an excellent way to deal with custom errors. It will display two parameters: the error message, and an error level.

syslog()

Example (using openlog() for the connection): Aug 4 11:42:10 vaprobash php: User #5 is logged from three different locations.

Magento PHP Log Format

Here are some common error levels that you can base on:

  • E_ERROR – These are critical errors that stop code proceedings.
  • E_WARNING – These errors can’t stop the proceeding, but the code might not work as expected.
  • E_PARSE – These are compile-time parse issues, like missing parentheses or semicolons.
  • E_NOTICE – This error will announce possible bugs, such as using a change that doesn’t exist. It means the variable is a typo or is not assigned the right way.

Magento Apache Logs

Magento Apache Error Logs

This is the place where Apache contains the record of any errors collected in processing requests received by the server. and it will show the details of what went wrong (and, often, how to adjust it).

The format of Magento Apache logs is often like below:

[Sat Oct 10 11:45:39.902022 2011] [core:error] [pid 35708:tid 4328636416] [client 72.15.99.184] File does not exist: /usr/local/apache2/htdocs/favicon.ico

Reading the Error Entry
  • The first item is the date and time of the notice: [Sat Oct 10 11:45:39.902022 2011]
  • The next is the module producing the notice and the severity level of that one: [core:error]
  • This part will show the process ID and, if appropriate, the thread ID of the process that experienced the condition: [pid 35708:tid 4328636416]
  • Next is the client ID address that generated the request: [client 72.15.99.184] 
  • Finally, the details of the error message: File does not exist: /usr/local/apache2/htdocs/favicon.ico
Magento Apache Access Logs

Common Log Format

An example configuration for the access log might look as follows.

LogFormat “%h %l %u %t ”%r” %>s %b” common

This configuration will record log entries in a format known as the Common Log Format (CLF). 

Common Log Format

The log file entries produced will show as below

  • 127.0.0.1 – frank [10/Oct/2000:13:55:36 -0700] “GET /apache_pb.gif HTTP/1.0” 200 2326
  • 127.0.0.1 (%h)
  • – (%l)
  • frank (%u)
  • [10/Oct/2000:13:55:36 -0700] (%t)
  • “GET /apache_pb.gif HTTP/1.0″ (”%r”)
  • 200 (%>s)
  • 2326 (%b)

Magento NGINX Logs

NGINX Error Logs

When NGINX comes up against any issue, such as in the configuration file, it will be recorded in the NGINX error log. So if NGINX is unable to start or suddenly stops, you should check the NGINX error logs.

Example: error_log /var/log/nginx/error.log warn;

  • Error_log: Shows the directive (error_log)
  • Log_file: Shows the absolute path of your log file ( /var/log/nginx/error.log)
  • Log_level: Shows the severity level for the error messages to be logged (warn)
NGINX Error Log Severity Levels

Some severity levels can be determined in the error_log directive. Below are severity levels ranging from low to high.

  • debug – Useful debugging information to help clarify where the problem happens.
  • info – Informational messages that can add value for the developers.
  • notice – Something ordinary happened that is worth noting.
  • warn – Something unexpected happened, but it is not a cause for big concern.
  • error – Something unsuccessful was happened
  • crit – There is a serious problem that needs focus on.
  • alert – Quik action is required.
  • emerg – The system is in and can not be used and requires immediate attention.
What is an NGINX Access Log?

The NGINX access log is the same as the error log in that it logs information. However, NGINX  manages the log of every request made by the client. The access_log directive uses the below syntax:

access_log log_file log_format;

  • Access_log: Clarify the directive
  • Log_file: Defines the location of the access.log file
  • Log_format: Can be clarified with using variables (default format is combined)

Example: access_log /var/log/nginx/access.log log_file combined;

Get Started with Magento 2 Logging

1st Method: Create Magento Log with Custom File

For Magento from Version 2.4.2 to before: 

$writer = new ZendLogWriterStream(BP . ‘/var/log/logfile.log’);

$logger = new ZendLogLogger();

$logger->addWriter($writer);

$logger->info(‘Simple Text Log’);

$logger->info(‘Array Log’.print_r($myArrayVar, true));

For Magento Version 2.4.2 after:

$writer = new LaminasLogWriterStream(BP . ‘/var/log/cloudwayscustom.log’);

$logger = new  LaminasLogLogger();

$logger->addWriter($writer);

$logger->info(‘text message’);

$logger->info(print_r($object->getData(), true));

For Magento Version 2.4.3 or later:

$writer = new Zend_Log_Writer_Stream(BP . ‘/var/log/custom.log’);

$logger = new Zend_Log();

$logger->addWriter($writer);

$logger->info(‘text message’);

$logger->info(print_r($object->getData(), true));

2nd Method: Define Magento Logger Class

Create the Magento 2 Logger Class

App/code/Cloudways/CustomLog/Logger/Logger.php

<?php

namespace Cloudways/CustomLogLogger;

class Logger extends MonologLogger

{

}

Create the Handler Class and Mention the Log File

<?xml version="1.0"?>






<config xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">

   <type name="CloudwaysCustomLogLoggerHandler">

       <arguments>

           <argument name="filesystem" xsi:type="object">MagentoFrameworkFilesystemDriverFile</argument>

       </arguments>

   </type>

   <type name="CloudwaysCustomLogLoggerLogger">

       <arguments>

           <argument name="name" xsi:type="string">Cloudways_Custom_Log</argument>

           <argument name="handlers"  xsi:type="array">

               <item name="system" xsi:type="object">CloudwaysCustomLogLoggerHandler</item>

           </argument>

       </arguments>

   </type>

</config>

Run the following commands:

php bin/magento setup:di:compile

php bin/magento cache:flush

Use Custom Magento 2 Log File in Your Module

Create any block such as Cloudways/CustomLog/Block/Test.php

<?php

namespace CloudwaysCustomLogBlock;

class Test extends MagentoFrameworkViewElementTemplate

{

    protected $_customLogger;

 

    public function __construct(

        MagentoBackendBlockTemplateContext $context,

        CloudwaysCustomLog LoggerLogger $customLogger,

        array $data = []

    )

    {        

        $this->_customLogger = $customLogger;

        parent::__construct($context, $data);

    }

 

    public function LogData()

    {

        //save data in var/log/custom.log

        $this->_customLogger->info('Message goes here');




       //add array in log

       $this->_customLogger->info('API Params', $params); 

    }

}
  1. }

Method 3: Magento Logger through Object Manager

Magento 2 uses Object Manager, which is responsible for creating and bringing back the external class objects like the Logger Interface. Using Object Manager as it blocks instantiation is not recommended. Developers mostly use new PHP files for logging valuable information.

Sample Code:

   $objectmanager = MagentoFrameworkAppObjectManager::getInstance();

    $objectmanager->get(‘PsrLogLoggerInterface’)->info(‘Testing Log’); //Print log in var/log/system.log

    $objectmanager->get(‘PsrLogLoggerInterface’)->debug(‘Testing Log’); //Print log in var/log/debug.log

Magento 2 Debug Logging

Magento 2 comes with the built-in log files such as system.log, debug.log, and exception.log. Before proceeding with any of these methods, guarantee your Magento store is in the default or develop mode, not in production mode. Magento will print and write the log to the debug log.

If you would like to change the default value in default and develop mode, you can use the following command:

  • bin/magento setup:config:set –enable-debug-logging=true|false
  • bin/magento cache:flush

Magento 2 Database Logging

Another functionality for recording the database activity is using the MagentoFrameworkDBLoggerInterface Class. Developers can easily write down code for the application but find difficulty in checking the data activity stored in the database. Magento 2 logs the Database logs in var/debug/db.log

You can use the following command to enable/disable database logging:

  • bin/magento dev:query-log:enable|disable
  • bin/magento cache:flush

Magento 2 Cron Logging

Magento 2.3 brings a feature for logging more information by creating separate cron log files that make developer debugging easier. But it considerably increases the system log file size as the application goes live.

By default, Magento 2 cron will log the info in var/log/cron.log.

To enable Syslog logging, you can use the command:

bin/magento setup:config:set –enable-syslog-logging=true

Conclusion 

Above article we mentioned the knowledge about Magento logger and detailed examples so all of you can understand and apply. Customizing logs can also support better management. Which means you can use them to make timely decisions and save your Magento store from many kinds of issues. 

ONEXT Digital – we’re proud of delivering quality-focused software products and solutions that improve your online businesses. Please don’t hesitate to contact and share your ideas with us. 

Read Also

A Complete Guide install Magento 2 on Windows on XAMPP server with GIT