Using JLog/ru: Difference between revisions

From Joomla! Documentation

Created page with "Логирование, в некоторой степени, может контролироваться динамически через глобальную конфигу..."
FuzzyBot (talk | contribs)
Updating to match new version of source page
 
(79 intermediate revisions by 2 users not shown)
Line 3: Line 3:
__TOC__
__TOC__
== Обзор ==
== Обзор ==
Логирование в Joomla дает вам возможность логировать сообщения в файлы и на экран (в консоли отладки Joomla внизу веб-страницы), а основным классом Joomla, который для этого используется, является JLog.  
<span class="mw-translate-fuzzy">Логирование в Joomla дает вам возможность логировать сообщения в файлы и на экран (в консоли отладки Joomla внизу веб-страницы), а основным классом Joomla, который для этого используется, является JLog.</span>


Логирование, в некоторой степени, может контролироваться динамически через глобальную конфигурацию Joomla и путем настройки плагина Система-Отладка (поставляется с Joomla). В целом эти возможности позволяют вам:
<div class="mw-translate-fuzzy">
* включать или отключать систему отладки - чтобы вы не потребляли ресурсы без необходимости, но при этом у вас оставалась информация, чтобы помочь в устранении неполадок, когда есть проблемы. Например, на живом сайте, на котором установлено ваше расширение.
Логирование, в некоторой степени, может контролироваться динамически через общие настройки Joomla и путем настройки плагина «Система - Отладка» (поставляется с Joomla). В целом эти возможности позволяют вам:
* включать или отключать систему отладки - чтобы вы не потребляли ресурсы без необходимости, но при этом у вас оставалась информация для того, чтобы помочь в устранении неполадок, когда есть проблемы. Например, на живом сайте, на котором установлено ваше расширение.
* направлять сообщения логов в определенный файл логов вашего собственного расширения
* направлять сообщения логов в определенный файл логов вашего собственного расширения
* просматривать сообщения логов в консоли отладки - вы можете выбрать группу пользователей, для которых должны отображаться сообщения логов, чтобы на живом сайте разработчики могли видеть сообщения, в то время как другие пользователи не затрагивались.
* просматривать сообщения логов в консоли отладки - вы можете выбрать группу пользователей, для которых должны отображаться сообщения логов, чтобы на живом сайте разработчики могли видеть сообщения, в то время как другие пользователи не затрагивались.
* фильтровать сообщения консоли отладки по приоритету (например, INFO, DEBUG, WARNING и т. д.) и по категориям (вы можете сами определять свои категории).
* фильтровать сообщения консоли отладки по приоритету (например, INFO, DEBUG, WARNING и т. д.) и по категориям (вы можете сами определять свои категории).
Кроме того, сообщения логов могут быть переведены на разные языки.  
Кроме того, сообщения логов могут быть переведены на разные языки.
</div>
* switch DEBUG logging on or off – so that ordinarily you don't consume resources needlessly, but you have the logging information to assist troubleshooting when there are issues, for example on a live site which has your extension installed.
* route log messages to a specific log file for your own extension.
* view log messages in the Debug Console – you can select the group of users to which log messages should be displayed, so that on a live site developers can see the messages while other users are unaffected.
* filter Debug Console messages by priority (i.e. INFO, DEBUG, WARNING and so on) and by category. (You are free to define your own categories.)
In addition, the log messages can be translatable into different languages.


The main configuration options relating to logging are shown below.
Основные параметры конфигурации, относящиеся к ведению логов, показаны ниже.
Включение отладки и отображение консоли отладки Joomla контролируется через общие настройки.


Switching on debug and display of the Joomla Debug Console is controlled through the global configuration options.
[[File:Global conf debug-en.jpg]]
[[File:Global conf debug-en.jpg]]


Logging to the general log file is controlled via the Logging tab of the configuration of the Joomla System - Debug plugin. (In the administrator menu click on Extensions / Plugins, find the System - Debug plugin, and click on it to edit its configurable options).  
<div class="mw-translate-fuzzy">
Логирование в общий файл логов контролируется с помощью вкладки Журнал (логи) конфигурации плагина Joomla «Система - Отладка» (в меню администратора нажмите «Расширения / Плагины», найдите плагин «Система - Отладка» и нажмите на него, чтобы изменить его параметры).
</div>
 
[[File:Debug logging settings-en.jpg]]
[[File:Debug logging settings-en.jpg]]


And the options within the Plugin tab control display on the Joomla Debug Console.
Параметры на вкладке "Плагин" контролируют отображение в консоли отладки Joomla.
 
[[File:Debug plugin settings-en.jpg]]
[[File:Debug plugin settings-en.jpg]]


== Базовое логирование в файл ==
Чтобы отправить сообщение в лог, используйте функцию <tt>JLog::add()</tt>. Например:
<source lang="php">
JLog::add('my error message', JLog::ERROR, 'my-error-category');
</source>
Using the new class naming convention use instead:
<source lang="php">
use Joomla\CMS\Log\Log;
Log::add('my error message', Log::ERROR, 'my-error-category');
</source>
<div class="mw-translate-fuzzy">
Параметры
# Строка сообщения. Вы можете использовать перевод, например, <tt>JText::_('MY_EXTENSION_ERR_MSG')</tt>. Вы также можете отображать значения переменных при условии, что вы конвертируете их в строковый формат (например, с помощью <tt>__toString ()</tt>, если тип переменной это поддерживает).
# Приоритет, который может быть одним из: JLog::EMERGENCY, JLog::ALERT, JLog::CRITICAL, JLog::ERROR, JLog::WARNING, JLog::NOTICE, JLog::INFO, JLog::DEBUG (основано на уровнях серьёзности syslog / RFC 5424 – подробнее в [https://ru.wikipedia.org/wiki/Syslog материале Wikipedia о syslog]).
# Категория, которая является просто текстовой строкой. Вы можете определить любые категории, которые вам нравятся. Лучше всего определять их, чтобы избежать возможных конфликтов с другими расширениями.
</div>
<span class="mw-translate-fuzzy">Если вы включите диагностические сообщения отладки в ваше расширение, то это может быть очень полезно при устранении неполадок. В этом случае добавьте к своему лог сообщению проверку на JDEBUG:</span>
<source lang="php">
if (JDEBUG)
{
    JLog::add('my debug message', JLog::DEBUG, 'my-debug-category');
}
</source>
== Basic Logging Sample Code ==
Below is the code for a simple Joomla module which you can install and run to demonstrate use of the logging functionality. If you are unsure about development and installing a Joomla module then following the tutorial at [[S:MyLanguage/J3.x:Creating a simple module/Introduction| Creating a simple module ]] will help.
In a folder mod_sample_log create the following 2 files:
<tt>mod_sample_log.xml</tt>
<source lang="xml">
<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="3.1" client="site" method="upgrade">
    <name>Joomla Log demo</name>
    <version>1.0.1</version>
    <description>Code demonstrating use of Joomla Log class to log messages</description>
    <files>
        <filename module="mod_sample_log">mod_sample_log.php</filename>
    </files>
</extension>
</source>
<tt>mod_sample_log.php</tt>
<source lang="php">
<?php
defined('_JEXEC') or die('Restricted Access');
use Joomla\CMS\Log\Log;
Log::add('my error message', Log::ERROR, 'my-error-category');


== Basic File Logging ==
JLog::add('my old error message', JLog::WARNING, 'my-old-error-category');


To log a message you use the <tt>JLog::add()</tt> function. For example:
echo "Error message logged";
</source>


    JLog::add('my error message', JLog::ERROR, 'my-error-category');
Zip up the mod_sample_log directory to create <tt>mod_sample_log.zip</tt>.


The parameters are
Within your Joomla administrator go to Install Extensions and via the Upload Package File tab select this zip file to install this sample log module.  
# A message string. You can use translation with these eg JText::_('MY_EXTENSION_ERR_MSG'), You can also display the values of variables, provided you convert them into a string format (eg using __toString() if the type of the variable supports that).
# A priority, which can be one of JLog::EMERGENCY, JLog::ALERT, JLog::CRITICAL, JLog::ERROR, JLog::WARNING, JLog::NOTICE, JLog::INFO, JLog::DEBUG (based on the standard syslog / RFC 5424 severity levels – see [https://en.wikipedia.org/wiki/Syslog wikipedia article on syslog]).
# A category, which is just a text string. You can define whatever categories you like, but best to define them to avoid possible clashes with those of other extensions.  


It can be very helpful with troubleshooting problems later if you include diagnostic debug messages in your extension. In this case, enclose your log message within a check for JDEBUG:
Make this module visible by editing it (click on it within the Modules page) then:
# making its status Published
# selecting a position on the page for it to be shown
# on the menu assignment tab specify the pages it should appear on


    if (JDEBUG)
Check the configuration of the settings shown at the top of this web page. In particular, ensure that the System – Debug plugin is enabled and that Log Almost Everything is set to Yes. Also note where the folder where your log files are stored.
    {
        JLog::add('my debug message', JLog::DEBUG, 'my-debug-category');
    }


== Logging a specific log file==
Display your Joomla site and you should then see the sample log module appearing. In your log file folder you should find your error messages in the everything.php file.
You can use <tt>JLog::addLogger()</tt> to set up logging to an additional log file, filtering the log messages to be sent there by priority (aka severity level) and/or category. The parameters of <tt>JLog::addLogger()</tt> are:
# an array with configuration details – including the name of the log file
# the severity levels to be logged in that file
# an array of the categories to be logged in that file (or if parameter 4 is set to <tt>true</tt> then this array defines the categories which are NOT to be logged in the file)
# (often omitted) a boolean specifying whether parameter 3 is an include list (the default, P4 = <tt>false</tt>) or an exclude list (P4 = <tt>true</tt>)


For example if you have developed a 'com_helloworld' extension you could use the following:
Also switch on the debug console and confirm that you can see the error messages in its Log Messages section.


    JLog::addLogger(
== Logging to a Specific Log File==
        array(
            // Sets file name
            'text_file' => 'com_helloworld.log.php'
        ),
            // Sets messages of all log levels to be sent to the file
        JLog::ALL,
            // The log category/categories which should be recorded in this file
            // In this case, it's just the one category from our extension, still
            // we need to put it inside an array
        array('com_helloworld')
    );


Then when you log a message, specify the category as 'com_helloworld', as in the example below
<div class="mw-translate-fuzzy">
Вы можете использовать <tt>JLog::addLogger()</tt>, чтобы настроить ведение логов в дополнительный файл логов, отфильтровывая сообщения логов по приоритету (уровень серьезности) и / или категории. Параметры <tt>JLog::addLogger()</tt>:


    JLog::add(JText::_('COM_HELLOWORLD_ERROR_MESSAGE_123'), JLog::ERROR, 'com_helloworld');
# массив с деталями конфигурации - включая имя файла логов
# уровни серьезности, которые будут логироваться в этом файле
# массив категорий, которые будут логироваться в этом файле (или если для параметра 4 установлено значение <tt>true</tt>, тогда этот массив определяет категории, которые НЕ должны регистрироваться в файле)
# (часто пропускается) логическое значение, указывающее, является ли параметр 3 списком включения (по умолчанию P4 = <tt>false</tt>) или списком исключения (P4 = <tt>true</tt>)
</div>


This will result in your log message being written to com_helloworld.log.php. If the System – Debug plugin settings have "Log Almost Everything" set to Yes, then the message will appear in the common everything.php log file as well.
For example, if you have developed a ''com_helloworld'' extension you could use the following:


'''Note:''' You may wish to combine this with the [[S:MyLanguage/Display error messages and notices|Display error messages and notices]] section to display visible error notifications to users.
<source lang="php">
JLog::addLogger(
    array(
        // Sets file name
        'text_file' => 'com_helloworld.log.php'
    ),
    // Sets messages of all log levels to be sent to the file.
    JLog::ALL,
    // The log category/categories which should be recorded in this file.
    // In this case, it's just the one category from our extension.
    // We still need to put it inside an array.
    array('com_helloworld')
);
</source>


You can also add an additional logger to capture only critical and emergency log notifications:
<div class="mw-translate-fuzzy">
Затем, когда вы логируете сообщение, укажите категорию 'com_helloworld', как в примере ниже
</div>


    JLog::addLogger(
<source lang="php">
        array(
JLog::add(JText::_('COM_HELLOWORLD_ERROR_MESSAGE_123'), JLog::ERROR, 'com_helloworld');
            // Sets file name
</source>
            'text_file' => 'com_helloworld.critical_emergency.php'
        ),
            // Sets critical and emergency log level messages to be sent to the file
        JLog::CRITICAL + JLog::EMERGENCY,
            // The log category which should be recorded in this file
        array('com_helloworld')
    );


You can also exclude a specific priority level from being included. For example, to log all but DEBUG messages:
<span class="mw-translate-fuzzy">Это приведет к тому, что ваше сообщение будет записано в com_helloworld.log.php. Если в настройках плагина «Система - Отладка» для параметра «Протоколировать все» задано значение «Да», то это сообщение появится и в общем файле журнала everything.php.</span>


    JLog::addLogger(
'''Примечание:''' Вы можете объединить это с [[S:MyLanguage/Display error messages and notices|Display error messages and notices]] для отображения видимых уведомлений об ошибках для пользователей.
        array(
            // Sets file name
            'text_file' => 'com_helloworld.all_but_debug.php'
        ),
            // Sets all but DEBUG log level messages to be sent to the file
        JLog::ALL & ~JLog::DEBUG,
            // The log category which should be recorded in this file
        array('com_helloworld')
    );


The JLog priority levels are implemented as separate bits of an integer, so you can use '''bitwise''' operations (bitwise AND, &; and bitwise NOT, ~) to calculate the appropriate log levels. <tt>JLog::All</tt> is a constant integer which has all the relevant bits set, so that all the Joomla priority levels are included.
Вы также можете добавить дополнительный логгер для сбора только критических и аварийных уведомлений:


== Formatting the logfile ==
<source lang="php">
JLog::addLogger(
    array(
        // Sets file name.
        'text_file' => 'com_helloworld.critical_emergency.php'
    ),
    // Sets critical and emergency log level messages to be sent to the file.
    JLog::CRITICAL + JLog::EMERGENCY,
    // The log category which should be recorded in this file.
    array('com_helloworld')
);
</source>


The first parameter to addLogger can have a few optional additional settings in addition to the <tt>text_file</tt> entry.
Вы также можете исключить определенный уровень приоритета от включения в файл логов. Например, чтобы логировать все сообщения кроме DEBUG:


There is for example the entry <tt>text_entry_format</tt>, specifying the format of each line in your logfile.
<source lang="php">
JLog::addLogger(
    array(
        // Sets file name.
        'text_file' => 'com_helloworld.all_but_debug.php'
    ),
    // Sets all but DEBUG log level messages to be sent to the file.
    JLog::ALL & ~JLog::DEBUG,
    // The log category which should be recorded in this file.
    array('com_helloworld')
);
</source>


The default format is:
<div class="mw-translate-fuzzy">
Уровни приоритета <tt>JLog</tt> реализованы в виде отдельных битов целого числа, поэтому вы можете использовать '''побитовые''' операции  (побитовое AND, &; и побитовое NOT, ~) для вычисления подходящих уровней логов. <tt>JLog::All</tt> является постоянным целым числом, в котором установлены все соответствующие биты, поэтому включены все уровни приоритета Joomla.
</div>
 
<div class="mw-translate-fuzzy">
== Форматирование файла логов ==
</div>
 
Первый параметр <tt>addLogger</tt> может иметь несколько необязательных дополнительных настроек в дополнение к параметру <tt>text_file</tt>.
 
<div class="mw-translate-fuzzy">
Например, есть параметр <tt>text_entry_format</tt>, указывающий формат каждой строки в вашем лог файле.
</div>
 
Формат по умолчанию:


     '{DATETIME} {PRIORITY}      {CATEGORY}      {MESSAGE}'
     '{DATETIME} {PRIORITY}      {CATEGORY}      {MESSAGE}'


Here is an example of a different format which shows how to omit the category:
Вот пример другого формата, который показывает, как пропустить категорию:


    JLog::addLogger(
<source lang="php">
        array(
JLog::addLogger(
            // Sets file name
    array(
            'text_file' => 'com_helloworld.critical_emergency.php',
        // Sets file name.
            // Sets the format of each line
        'text_file' => 'com_helloworld.critical_emergency.php',
            'text_entry_format' => '{DATETIME} {PRIORITY} {MESSAGE}'
        // Sets the format of each line.
        ),
        'text_entry_format' => '{DATETIME} {PRIORITY} {MESSAGE}'
            // Sets all but DEBUG log level messages to be sent to the file
    ),
        JLog::ALL & ~JLog::DEBUG,
    // Sets all but DEBUG log level messages to be sent to the file.
            // The log category which should be recorded in this file
    JLog::ALL & ~JLog::DEBUG,
        array('com_helloworld')
    // The log category which should be recorded in this file.
    );
    array('com_helloworld')
);
</source>


In addition to the placeholders shown above in the default string, the following values are available:
Помимо заполнителей (placeholders), показанных выше в строке по умолчанию, доступны следующие значения:


     {CLIENTIP}      (this is the IP address of the client)
     {CLIENTIP}      (this is the IP address of the client)
Line 131: Line 223:
     {DATE}
     {DATE}


 
Существует дополнительный необязательный логический параметр <tt>text_file_no_php</tt>, который указывает, следует ли добавлять в файл логов обычный префикс:
There is an additional optional boolean parameter <tt>text_file_no_php</tt>, which specifies whether the log file is prepended with the usual prefix of:


     #
     #
     #<?php die('Forbidden.');?>
     #<?php die('Forbidden.');?>


'''Note:''' Usually you should not set this setting to false. Log files should not be readable from the outside, since they can provide valuable information about your system for attackers.
<div class="mw-translate-fuzzy">
Only dabble with this if you know what you're doing!
'''Примечание:''' Обычно вам не следует устанавливать для этого параметра значение <tt>false</tt>. Файлы логов не должны быть доступны для чтения извне, поскольку они могут предоставить злоумышленникам ценную информацию о вашей системе.
Изменяйте этот параметр, только если вы знаете, что делаете!
</div>
 
<div class="mw-translate-fuzzy">
Кроме того, если вы хотите сохранить файл логов где-то еще, а не по пути, указанному в общих настройках Joomla, вы можете изменить параметр <tt>text_file_path</tt>.
</div>
 
<div class="mw-translate-fuzzy">
== Логирование в другие места ==
</div>


Furthermore, if you want to store the log file somewhere else than the logging path configured in the Joomla! settings, you can there is the <tt>text_file_path</tt> setting.
<div class="mw-translate-fuzzy">
Помимо логирования в файлы, вы также можете логировать в другие места, такие как
* область сообщений Joomla (сообщение отображается, если вы вызываете <tt>JFactory::getApplication()->enqueueMessage()</tt>)
* таблица базы данных
* просто echo
Из них, пожалуй, наиболее полезным является логирование в панель сообщений, которое можно настроить следующим образом:
    JLog::addLogger(array('logger' => 'messagequeue'), JLog::ALL, array('msg-error-cat'));
Затем, когда вы делаете:
    JLog::add('сообщение об ошибке для отображения', JLog::ERROR, 'msg-error-cat');
вы получаете сообщение, скопированное на панель сообщений.
</div>
<div class="mw-translate-fuzzy">
'''Обратите внимание, что код ядра Joomla настраивает запись в очередь сообщений для категории 'jerror', поэтому, если вы используете эту категорию в своих сообщениях журнала, вы получите сообщение, отображаемое на панели сообщений.'''


== Logging to other places ==
Например:
    JLog::add ('ошибка скопирована на панель сообщений', JLog::ERROR, 'jerror');
приведет к тому, что сообщение будет отображаться в области сообщений Joomla, даже если вы явно не настроили такое поведение для своего логгера.
</div>


As well as logging to files, you can log to other places as well, such as
== PSR-3 Logger ==
* the Joomla message area (where the message is shown if you call <tt>JFactory::getApplication()->enqueueMessage()</tt>)
Since version 3.8 Joomla incorporates a logger which adheres to the [https://www.php-fig.org/psr/psr-3/ PSR-3 Logger Interface]. This enables libraries which follow this standard recommendation to integrate with the Joomla logging system. To use this, first do:
* a database table
* just a simple echo statement
Of these, probably the most useful is the logging to the message bar, which you can set up via:
    JLog::addLogger(array('logger' => 'messagequeue'), JLog::ALL, array('msg-error-cat'));
Then when you do
    JLog::add('an error to display', JLog::ERROR, 'msg-error-cat');
you will get the message copied to the message bar.


'''Note that Joomla core code sets up logging to the messagequeue for category 'jerror', so that if you use this category in your log messages, you will get the message displayed on the message bar.''' Eg
<source lang="php">
    JLog::add('error copied to message bar', JLog::Error, 'jerror');
use Joomla\CMS\Log\Log;
will result in the message being shown in the Joomla message area, even though you haven't explicitly set up a logger to log there.
$psr3Logger = Log::createDelegatedLogger();
</source>
This returns an object on which you have available the methods of the PSR-3 <tt>LoggerInterface</tt>, for example:


== Exceptions ==
<source lang="php">
$psr3Logger->critical("critical error text", array("category" => "my-critical-category"));
</source>
The default Joomla loggers process only the "category" and "date" elements of the <tt>context</tt> associative array (parameter 2), mapping the values of these elements to the corresponding column in your log file.


<code>JLog::add()</code> will throw an exception if it can't write to the log file. To avoid this, you'd have to either wrap the call in another function, or implement your own logger class and then include it with:
== Исключения ==


    JLog::addLogger(
<div class="mw-translate-fuzzy">
        array(
<code>JLog::add()</code> кидает исключение, если не может записать в файл логов. Чтобы избежать этого, вам придется либо обернуть вызов в другую функцию, либо реализовать свой собственный класс логгера, а затем включить его:
            // Use mycustomlogger
</div>
            'logger' => 'mycustomlogger',
            'text_file' => 'com_helloworld.errors.php'
        ),
        JLog::ALL,
        array('com_helloworld')
    );


== Further Reading ==  
<source lang="php">
Joomla logging should be used in tandem with PHP exceptions, not as a replacement. See [[S:MyLanguage/Exceptions and Logging in Joomla 1.7 and Joomla Platform 11.1|Exceptions and Logging in Joomla 1.7 and Joomla Platform 11.1]] for more information on this.
JLog::addLogger(
    array(
        // Use mycustomlogger.
        'logger' => 'mycustomlogger',
        'text_file' => 'com_helloworld.errors.php'
    ),
    JLog::ALL,
    array('com_helloworld')
);
</source>
== Что ещё почитать ==


Another tutorial (a little out of date, but still useful) is at [http://eddify.me/posts/logging-in-joomla-with-jlog.html logging in joomla with jlog].
<div class="mw-translate-fuzzy">
Логирование в Joomla должно использоваться в тандеме с исключениями PHP, а не в качестве замены. Подробнее в [[S:MyLanguage/Exceptions and Logging in Joomla 1.7 and Joomla Platform 11.1|Exceptions and Logging in Joomla 1.7 and Joomla Platform 11.1]].
</div>


<noinclude>
<noinclude>

Latest revision as of 15:17, 31 March 2020

Обзор

Логирование в Joomla дает вам возможность логировать сообщения в файлы и на экран (в консоли отладки Joomla внизу веб-страницы), а основным классом Joomla, который для этого используется, является JLog.

Логирование, в некоторой степени, может контролироваться динамически через общие настройки Joomla и путем настройки плагина «Система - Отладка» (поставляется с Joomla). В целом эти возможности позволяют вам:

  • включать или отключать систему отладки - чтобы вы не потребляли ресурсы без необходимости, но при этом у вас оставалась информация для того, чтобы помочь в устранении неполадок, когда есть проблемы. Например, на живом сайте, на котором установлено ваше расширение.
  • направлять сообщения логов в определенный файл логов вашего собственного расширения
  • просматривать сообщения логов в консоли отладки - вы можете выбрать группу пользователей, для которых должны отображаться сообщения логов, чтобы на живом сайте разработчики могли видеть сообщения, в то время как другие пользователи не затрагивались.
  • фильтровать сообщения консоли отладки по приоритету (например, INFO, DEBUG, WARNING и т. д.) и по категориям (вы можете сами определять свои категории).

Кроме того, сообщения логов могут быть переведены на разные языки.

  • switch DEBUG logging on or off – so that ordinarily you don't consume resources needlessly, but you have the logging information to assist troubleshooting when there are issues, for example on a live site which has your extension installed.
  • route log messages to a specific log file for your own extension.
  • view log messages in the Debug Console – you can select the group of users to which log messages should be displayed, so that on a live site developers can see the messages while other users are unaffected.
  • filter Debug Console messages by priority (i.e. INFO, DEBUG, WARNING and so on) and by category. (You are free to define your own categories.)

In addition, the log messages can be translatable into different languages.

Основные параметры конфигурации, относящиеся к ведению логов, показаны ниже. Включение отладки и отображение консоли отладки Joomla контролируется через общие настройки.

Логирование в общий файл логов контролируется с помощью вкладки Журнал (логи) конфигурации плагина Joomla «Система - Отладка» (в меню администратора нажмите «Расширения / Плагины», найдите плагин «Система - Отладка» и нажмите на него, чтобы изменить его параметры).

Параметры на вкладке "Плагин" контролируют отображение в консоли отладки Joomla.

Базовое логирование в файл

Чтобы отправить сообщение в лог, используйте функцию JLog::add(). Например:

JLog::add('my error message', JLog::ERROR, 'my-error-category');

Using the new class naming convention use instead:

use Joomla\CMS\Log\Log;
Log::add('my error message', Log::ERROR, 'my-error-category');

Параметры

  1. Строка сообщения. Вы можете использовать перевод, например, JText::_('MY_EXTENSION_ERR_MSG'). Вы также можете отображать значения переменных при условии, что вы конвертируете их в строковый формат (например, с помощью __toString (), если тип переменной это поддерживает).
  2. Приоритет, который может быть одним из: JLog::EMERGENCY, JLog::ALERT, JLog::CRITICAL, JLog::ERROR, JLog::WARNING, JLog::NOTICE, JLog::INFO, JLog::DEBUG (основано на уровнях серьёзности syslog / RFC 5424 – подробнее в материале Wikipedia о syslog).
  3. Категория, которая является просто текстовой строкой. Вы можете определить любые категории, которые вам нравятся. Лучше всего определять их, чтобы избежать возможных конфликтов с другими расширениями.

Если вы включите диагностические сообщения отладки в ваше расширение, то это может быть очень полезно при устранении неполадок. В этом случае добавьте к своему лог сообщению проверку на JDEBUG:

if (JDEBUG)
{
    JLog::add('my debug message', JLog::DEBUG, 'my-debug-category');
}

Basic Logging Sample Code

Below is the code for a simple Joomla module which you can install and run to demonstrate use of the logging functionality. If you are unsure about development and installing a Joomla module then following the tutorial at Creating a simple module will help.

In a folder mod_sample_log create the following 2 files:

mod_sample_log.xml

<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="3.1" client="site" method="upgrade">
    <name>Joomla Log demo</name>
    <version>1.0.1</version>
    <description>Code demonstrating use of Joomla Log class to log messages</description>
    <files>
        <filename module="mod_sample_log">mod_sample_log.php</filename>
    </files>
</extension>

mod_sample_log.php

<?php
defined('_JEXEC') or die('Restricted Access');

use Joomla\CMS\Log\Log;

Log::add('my error message', Log::ERROR, 'my-error-category');

JLog::add('my old error message', JLog::WARNING, 'my-old-error-category');

echo "Error message logged";

Zip up the mod_sample_log directory to create mod_sample_log.zip.

Within your Joomla administrator go to Install Extensions and via the Upload Package File tab select this zip file to install this sample log module.

Make this module visible by editing it (click on it within the Modules page) then:

  1. making its status Published
  2. selecting a position on the page for it to be shown
  3. on the menu assignment tab specify the pages it should appear on

Check the configuration of the settings shown at the top of this web page. In particular, ensure that the System – Debug plugin is enabled and that Log Almost Everything is set to Yes. Also note where the folder where your log files are stored.

Display your Joomla site and you should then see the sample log module appearing. In your log file folder you should find your error messages in the everything.php file.

Also switch on the debug console and confirm that you can see the error messages in its Log Messages section.

Logging to a Specific Log File

Вы можете использовать JLog::addLogger(), чтобы настроить ведение логов в дополнительный файл логов, отфильтровывая сообщения логов по приоритету (уровень серьезности) и / или категории. Параметры JLog::addLogger():

  1. массив с деталями конфигурации - включая имя файла логов
  2. уровни серьезности, которые будут логироваться в этом файле
  3. массив категорий, которые будут логироваться в этом файле (или если для параметра 4 установлено значение true, тогда этот массив определяет категории, которые НЕ должны регистрироваться в файле)
  4. (часто пропускается) логическое значение, указывающее, является ли параметр 3 списком включения (по умолчанию P4 = false) или списком исключения (P4 = true)

For example, if you have developed a com_helloworld extension you could use the following:

JLog::addLogger(
    array(
         // Sets file name
         'text_file' => 'com_helloworld.log.php'
    ),
    // Sets messages of all log levels to be sent to the file.
    JLog::ALL,
    // The log category/categories which should be recorded in this file.
    // In this case, it's just the one category from our extension.
    // We still need to put it inside an array.
    array('com_helloworld')
);

Затем, когда вы логируете сообщение, укажите категорию 'com_helloworld', как в примере ниже

JLog::add(JText::_('COM_HELLOWORLD_ERROR_MESSAGE_123'), JLog::ERROR, 'com_helloworld');

Это приведет к тому, что ваше сообщение будет записано в com_helloworld.log.php. Если в настройках плагина «Система - Отладка» для параметра «Протоколировать все» задано значение «Да», то это сообщение появится и в общем файле журнала everything.php.

Примечание: Вы можете объединить это с Display error messages and notices для отображения видимых уведомлений об ошибках для пользователей.

Вы также можете добавить дополнительный логгер для сбора только критических и аварийных уведомлений:

JLog::addLogger(
    array(
         // Sets file name.
         'text_file' => 'com_helloworld.critical_emergency.php'
    ),
    // Sets critical and emergency log level messages to be sent to the file.
    JLog::CRITICAL + JLog::EMERGENCY,
    // The log category which should be recorded in this file.
    array('com_helloworld')
);

Вы также можете исключить определенный уровень приоритета от включения в файл логов. Например, чтобы логировать все сообщения кроме DEBUG:

JLog::addLogger(
    array(
         // Sets file name.
         'text_file' => 'com_helloworld.all_but_debug.php'
    ),
    // Sets all but DEBUG log level messages to be sent to the file.
    JLog::ALL & ~JLog::DEBUG,
    // The log category which should be recorded in this file.
    array('com_helloworld')
);

Уровни приоритета JLog реализованы в виде отдельных битов целого числа, поэтому вы можете использовать побитовые операции (побитовое AND, &; и побитовое NOT, ~) для вычисления подходящих уровней логов. JLog::All является постоянным целым числом, в котором установлены все соответствующие биты, поэтому включены все уровни приоритета Joomla.

Форматирование файла логов

Первый параметр addLogger может иметь несколько необязательных дополнительных настроек в дополнение к параметру text_file.

Например, есть параметр text_entry_format, указывающий формат каждой строки в вашем лог файле.

Формат по умолчанию:

   '{DATETIME} {PRIORITY}      {CATEGORY}      {MESSAGE}'

Вот пример другого формата, который показывает, как пропустить категорию:

JLog::addLogger(
    array(
         // Sets file name.
         'text_file' => 'com_helloworld.critical_emergency.php',
         // Sets the format of each line.
         'text_entry_format' => '{DATETIME} {PRIORITY} {MESSAGE}'
    ),
    // Sets all but DEBUG log level messages to be sent to the file.
    JLog::ALL & ~JLog::DEBUG,
    // The log category which should be recorded in this file.
    array('com_helloworld')
);

Помимо заполнителей (placeholders), показанных выше в строке по умолчанию, доступны следующие значения:

   {CLIENTIP}      (this is the IP address of the client)
   {TIME}
   {DATE}

Существует дополнительный необязательный логический параметр text_file_no_php, который указывает, следует ли добавлять в файл логов обычный префикс:

   #
   #<?php die('Forbidden.');?>

Примечание: Обычно вам не следует устанавливать для этого параметра значение false. Файлы логов не должны быть доступны для чтения извне, поскольку они могут предоставить злоумышленникам ценную информацию о вашей системе. Изменяйте этот параметр, только если вы знаете, что делаете!

Кроме того, если вы хотите сохранить файл логов где-то еще, а не по пути, указанному в общих настройках Joomla, вы можете изменить параметр text_file_path.

Логирование в другие места

Помимо логирования в файлы, вы также можете логировать в другие места, такие как

  • область сообщений Joomla (сообщение отображается, если вы вызываете JFactory::getApplication()->enqueueMessage())
  • таблица базы данных
  • просто echo

Из них, пожалуй, наиболее полезным является логирование в панель сообщений, которое можно настроить следующим образом:

    JLog::addLogger(array('logger' => 'messagequeue'), JLog::ALL, array('msg-error-cat'));

Затем, когда вы делаете:

    JLog::add('сообщение об ошибке для отображения', JLog::ERROR, 'msg-error-cat');

вы получаете сообщение, скопированное на панель сообщений.

Обратите внимание, что код ядра Joomla настраивает запись в очередь сообщений для категории 'jerror', поэтому, если вы используете эту категорию в своих сообщениях журнала, вы получите сообщение, отображаемое на панели сообщений.

Например:

    JLog::add ('ошибка скопирована на панель сообщений', JLog::ERROR, 'jerror');

приведет к тому, что сообщение будет отображаться в области сообщений Joomla, даже если вы явно не настроили такое поведение для своего логгера.

PSR-3 Logger

Since version 3.8 Joomla incorporates a logger which adheres to the PSR-3 Logger Interface. This enables libraries which follow this standard recommendation to integrate with the Joomla logging system. To use this, first do:

use Joomla\CMS\Log\Log;
$psr3Logger = Log::createDelegatedLogger();

This returns an object on which you have available the methods of the PSR-3 LoggerInterface, for example:

$psr3Logger->critical("critical error text", array("category" => "my-critical-category"));

The default Joomla loggers process only the "category" and "date" elements of the context associative array (parameter 2), mapping the values of these elements to the corresponding column in your log file.

Исключения

JLog::add() кидает исключение, если не может записать в файл логов. Чтобы избежать этого, вам придется либо обернуть вызов в другую функцию, либо реализовать свой собственный класс логгера, а затем включить его:

JLog::addLogger(
    array(
         // Use mycustomlogger.
         'logger' => 'mycustomlogger',
         'text_file' => 'com_helloworld.errors.php'
    ),
    JLog::ALL,
    array('com_helloworld')
);

Что ещё почитать

Логирование в Joomla должно использоваться в тандеме с исключениями PHP, а не в качестве замены. Подробнее в Exceptions and Logging in Joomla 1.7 and Joomla Platform 11.1.