Difference between revisions of "Using JLog"

From Joomla! Documentation

(Marked this version for translation)
 
(43 intermediate revisions by 10 users not shown)
Line 1: Line 1:
{{version|1.7,2.5,3.0|platform=11.1,11.4,12.1}}{{RightTOC}}
+
<noinclude><languages /></noinclude>
Using JLog can be very useful in components when analysing the performance of custom extensions - or analysing where extensions are giving issues. Note this should be used in tandem with php exceptions - not as a replacement. See [[Exceptions and Logging in Joomla 1.7 and Joomla Platform 11.1]] for more information on this
 
  
== Calling the class ==
+
__TOC__
 +
<translate>
 +
== Overview == <!--T:27-->
 +
</translate>
 +
<translate><!--T:28--> Joomla logging gives you the ability to log messages to files and to the screen (within the Joomla! Debug Console at the bottom of the web page) and the main Joomla class which underpins this is JLog. In the new naming convention this is the Log class within the namespace Joomla\CMS\Log\Log.</translate>
  
To use JLog you need to call the JLog class. Done through the following code:
+
<translate><!--T:29-->
 +
The logging can be controlled dynamically through the Joomla Global Configuration and by configuring the System – Debug plugin (which is shipped with Joomla). Overall these facilities allow you to:</translate>
 +
<translate>
 +
<!--T:53-->
 +
* 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.</translate>
  
    jimport('joomla.log.log');
+
<translate><!--T:30-->
 +
The main configuration options relating to logging are shown below.</translate>
 +
<translate>
 +
<!--T:31-->
 +
Switching on debug and display of the Joomla Debug Console is controlled through the global configuration options.
 +
</translate>
  
== Basic File Logging ==
+
[[File:Global conf debug-<translate><!--T:32--> en</translate>.jpg]]
  
Often you may wish to display an error log message and log to an error file. Joomla allows this natively through the [[JLog::add]] function. For example:
+
<translate><!--T:33-->
 +
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. Click on it to edit its configurable options).
 +
</translate>
  
    JLog::add(JText::_('JTEXT_ERROR_MESSAGE'), JLog::WARNING, 'jerror');
+
[[File:Debug logging settings-<translate><!--T:34--> en</translate>.jpg]]
  
Adding the category of jerror means that this message will also be displayed to users. To only write to file you can easily drop that parameter and simply use
+
<translate><!--T:35-->
 +
And the options within the Plugin tab control display on the Joomla Debug Console.
 +
</translate>
  
    JLog::add(JText::_('JTEXT_ERROR_MESSAGE'), JLog::WARNING, 'jerror');
+
[[File:Debug plugin settings-<translate><!--T:36--> en</translate>.jpg]]
  
== Logging a specific extension ==
+
<translate>
Sometimes it may be useful to log the errors to a specific file. In this case you can
+
== Basic File Logging == <!--T:4-->
 +
</translate>
  
    JLog::addLogger(
+
<translate>
        array(
+
<!--T:37-->
            //Sets file name
+
To log a message you use the <tt>JLog::add()</tt> function. For example:</translate>
            'text_file' => 'com_helloworld.errors.php'
 
        ),
 
        //Sets all JLog messages to be set to the file
 
        JLog::ALL,
 
        //Chooses a category name
 
        'com_helloworld'
 
    );
 
  
Now remember to change the category when you add a log. Such as in the example below.
+
<source lang="php">
 +
JLog::add('my error message', JLog::ERROR, 'my-error-category');
 +
</source>
  
    JLog::add(JText::_('JTEXT_ERROR_MESSAGE'), JLog::WARNING, 'com_helloworld');
+
<translate>
 +
<!--T:54-->
 +
Using the new class naming convention use instead:</translate>
 +
<source lang="php">
 +
use Joomla\CMS\Log\Log;
 +
Log::add('my error message', Log::ERROR, 'my-error-category');
 +
</source>
  
Note you may wish to combine this with the [[Display error messages and notices]] section to display visable error notifications to users.
+
<translate><!--T:38-->
 +
The parameters are
 +
# A message string. You can use translation with these. (For example, JText::_('MY_EXTENSION_ERR_MSG') You can also display the values of variables, provided you convert them into a string format. (For  example, 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 it is best to define them to avoid possible clashes with those of other extensions.
 +
</translate>
  
[[Category:Development]]
+
<translate><!--T:39--> It can be very helpful with troubleshooting problems if you include diagnostic debug messages in your extension. In this case, enclose your log message within a check for JDEBUG:</translate>
[[category:Joomla! 1.7]]
+
 
[[category:Joomla! 2.5]]
+
<source lang="php">
[[category:Joomla! 3.0]]
+
if (JDEBUG)
 +
{
 +
    JLog::add('my debug message', JLog::DEBUG, 'my-debug-category');
 +
}
 +
</source>
 +
 
 +
<translate>
 +
== Basic Logging Sample Code == <!--T:55-->
 +
</translate>
 +
 
 +
<translate><!--T:56--> 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.</translate>
 +
 
 +
<translate><!--T:57--> In a folder mod_sample_log create the following 2 files:</translate>
 +
 
 +
<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');
 +
 
 +
JLog::add('my old error message', JLog::WARNING, 'my-old-error-category');
 +
 
 +
echo "Error message logged";
 +
</source>
 +
 
 +
<translate><!--T:58--> Zip up the mod_sample_log directory to create <tt>mod_sample_log.zip</tt>.</translate>
 +
 
 +
<translate><!--T:59--> 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.</translate>
 +
 
 +
<translate><!--T:60-->
 +
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</translate>
 +
 
 +
<translate><!--T:61--> 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.</translate>
 +
 
 +
<translate><!--T:62--> 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.</translate>
 +
 
 +
<translate><!--T:63--> Also switch on the debug console and confirm that you can see the error messages in its Log Messages section.</translate>
 +
 
 +
<translate>
 +
== Logging to a Specific Log File== <!--T:64-->
 +
</translate>
 +
 
 +
<translate>
 +
<!--T:41-->
 +
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 (the '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. (If parameter 4 is set to <tt>true</tt>, 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>.)
 +
</translate>
 +
 
 +
<translate><!--T:65--> For example, if you have developed a ''com_helloworld'' extension you could use the following:</translate>
 +
 
 +
<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>
 +
 
 +
<translate>
 +
<!--T:43-->
 +
Then when you log a message, specify the category as ''com_helloworld'', as in the example below</translate>
 +
 
 +
<source lang="php">
 +
JLog::add(JText::_('COM_HELLOWORLD_ERROR_MESSAGE_123'), JLog::ERROR, 'com_helloworld');
 +
</source>
 +
 
 +
<translate><!--T:44--> 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, the message will appear in the common ''everything.php'' log file as well.</translate>
 +
 
 +
<translate><!--T:10-->
 +
'''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.</translate>
 +
 
 +
<translate><!--T:12-->
 +
You can also add an additional logger to capture only critical and emergency log notifications:</translate>
 +
 
 +
<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>
 +
 
 +
<translate>
 +
<!--T:45-->
 +
You can also exclude a specific priority level from being included. For example, to log all but DEBUG messages:</translate>
 +
 
 +
<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>
 +
 
 +
<translate>
 +
<!--T:46-->
 +
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.</translate>
 +
 
 +
<translate>
 +
== Formatting the Log File == <!--T:15-->
 +
</translate>
 +
 
 +
<translate><!--T:16-->
 +
The first parameter to addLogger can have a few optional additional settings in addition to the <tt>text_file</tt> entry.</translate>
 +
 
 +
<translate><!--T:17-->
 +
There is, for example, the entry <tt>text_entry_format</tt>, specifying the format of each line in your log file.</translate>
 +
 
 +
<translate><!--T:18-->
 +
The default format is:</translate>
 +
 
 +
    '{DATETIME} {PRIORITY}      {CATEGORY}      {MESSAGE}'
 +
 
 +
<translate><!--T:19-->
 +
Here is an example of a different format which shows how to omit the category:</translate>
 +
 
 +
<source lang="php">
 +
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')
 +
);
 +
</source>
 +
 
 +
<translate><!--T:20-->
 +
In addition to the placeholders shown above in the default string, the following values are available:</translate>
 +
 
 +
    {CLIENTIP}      (this is the IP address of the client)
 +
    {TIME}
 +
    {DATE}
 +
 
 +
<translate><!--T:21-->
 +
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:</translate>
 +
 
 +
    #
 +
    #<?php die('Forbidden.');?>
 +
 
 +
<translate><!--T:22-->
 +
'''Note:''' Usually you should not set this setting to false. Log files should not be readable from the outside. They can provide valuable information about your system for attackers.
 +
Only dabble with this if you know what you're doing!</translate>
 +
 
 +
<translate><!--T:23-->
 +
Furthermore, if you want to store the log file somewhere other than the logging path configured in the Joomla! settings, there is the <tt>text_file_path</tt> setting.</translate>
 +
 
 +
<translate>
 +
== Logging to Other Places == <!--T:47-->
 +
</translate>
 +
 
 +
<translate>
 +
<!--T:48-->
 +
As well as logging to files, you can log to other places as well, such as
 +
* the Joomla message area (where the message is shown if you call <source lang="php" inline>JFactory::getApplication()->enqueueMessage()</source>).
 +
* 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:
 +
<source lang="php">
 +
JLog::addLogger(array('logger' => 'messagequeue'), JLog::ALL, array('msg-error-cat'));
 +
</source>
 +
Then when you do:
 +
<source lang="php">
 +
JLog::add('an error to display', JLog::ERROR, 'msg-error-cat');
 +
</source>
 +
you will get the message copied to the message bar.</translate>
 +
<translate>
 +
<!--T:49-->
 +
'''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.''' For example:
 +
<source lang="php">
 +
JLog::add('error copied to message bar', JLog::Error, 'jerror');
 +
</source>
 +
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.
 +
</translate>
 +
 
 +
<translate>
 +
== PSR-3 Logger == <!--T:66--></translate>
 +
<translate>
 +
<!--T:67-->
 +
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:</translate>
 +
 
 +
<source lang="php">
 +
use Joomla\CMS\Log\Log;
 +
$psr3Logger = Log::createDelegatedLogger();
 +
</source>
 +
<translate>
 +
<!--T:68-->
 +
This returns an object on which you have available the methods of the PSR-3 <tt>LoggerInterface</tt>, for example:</translate>
 +
 
 +
<source lang="php">
 +
$psr3Logger->critical("critical error text", array("category" => "my-critical-category"));
 +
</source>
 +
<translate>
 +
<!--T:69-->
 +
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. </translate>
 +
 
 +
<translate>
 +
== Exceptions == <!--T:25-->
 +
</translate>
 +
 
 +
<translate><!--T:26-->
 +
<source lang="php" inline>JLog::add()</source> 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:</translate>
 +
 
 +
<source lang="php">
 +
JLog::addLogger(
 +
    array(
 +
        // Use mycustomlogger.
 +
        'logger' => 'mycustomlogger',
 +
        'text_file' => 'com_helloworld.errors.php'
 +
    ),
 +
    JLog::ALL,
 +
    array('com_helloworld')
 +
);
 +
</source>
 +
<translate>
 +
== Further Reading == <!--T:50-->
 +
</translate>
 +
 
 +
<translate>
 +
<!--T:51-->
 +
Joomla logging should be used in tandem with PHP exceptions, not as a replacement. See [[J2.5:Exceptions_and_Logging_in_Joomla_Platform_11.1_and_Joomla_2.5]] for backstory on this class and how it arose from the old Joomla PHP4 compatible error classes.
 +
</translate>
 +
 
 +
<noinclude>
 +
[[Category:Development{{#translation:}}]]
 +
[[category:Joomla! 1.7{{#translation:}}]]
 +
[[category:Joomla! 2.5{{#translation:}}]]
 +
[[category:Joomla! 3.0{{#translation:}}]]
 +
[[category:Joomla! 3.x{{#translation:}}]]
 +
</noinclude>

Latest revision as of 10:16, 31 March 2020

Other languages:
Deutsch • ‎English • ‎Nederlands • ‎español • ‎français • ‎русский

Overview[edit]

Joomla logging gives you the ability to log messages to files and to the screen (within the Joomla! Debug Console at the bottom of the web page) and the main Joomla class which underpins this is JLog. In the new naming convention this is the Log class within the namespace Joomla\CMS\Log\Log.

The logging can be controlled dynamically through the Joomla Global Configuration and by configuring the System – Debug plugin (which is shipped with Joomla). Overall these facilities allow you to:

  • 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. Switching on debug and display of the Joomla Debug Console is controlled through the global configuration options.

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. Click on it to edit its configurable options).

Debug logging settings-en.jpg

And the options within the Plugin tab control display on the Joomla Debug Console.

Debug plugin settings-en.jpg

Basic File Logging[edit]

To log a message you use the JLog::add() function. For example:

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');

The parameters are

  1. A message string. You can use translation with these. (For example, JText::_('MY_EXTENSION_ERR_MSG') You can also display the values of variables, provided you convert them into a string format. (For example, using __toString() if the type of the variable supports that.)
  2. 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 wikipedia article on syslog).
  3. A category, which is just a text string. You can define whatever categories you like, but it is best to define them to avoid possible clashes with those of other extensions.

It can be very helpful with troubleshooting problems if you include diagnostic debug messages in your extension. In this case, enclose your log message within a check for JDEBUG:

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

Basic Logging Sample Code[edit]

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[edit]

You can use JLog::addLogger() to set up logging to an additional log file, filtering the log messages to be sent there by priority (the 'severity level') and/or category. The parameters of JLog::addLogger() are:

  1. an array with configuration details – including the name of the log file.
  2. the severity levels to be logged in that file.
  3. an array of the categories to be logged in that file. (If parameter 4 is set to true, this array defines the categories which are NOT to be logged in the file.)
  4. (often omitted) a boolean specifying whether parameter 3 is an include list. (The default, P4 = false) or an exclude list (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')
);

Then when you log a message, specify the category as com_helloworld, as in the example below

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

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, the message will appear in the common everything.php log file as well.

Note: You may wish to combine this with the Display error messages and notices section to display visible error notifications to users.

You can also add an additional logger to capture only critical and emergency log notifications:

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')
);

You can also exclude a specific priority level from being included. For example, to log all but DEBUG messages:

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')
);

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. JLog::All is a constant integer which has all the relevant bits set, so that all the Joomla priority levels are included.

Formatting the Log File[edit]

The first parameter to addLogger can have a few optional additional settings in addition to the text_file entry.

There is, for example, the entry text_entry_format, specifying the format of each line in your log file.

The default format is:

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

Here is an example of a different format which shows how to omit the category:

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')
);

In addition to the placeholders shown above in the default string, the following values are available:

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

There is an additional optional boolean parameter text_file_no_php, which specifies whether the log file is prepended with the usual prefix of:

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

Note: Usually you should not set this setting to false. Log files should not be readable from the outside. They can provide valuable information about your system for attackers. Only dabble with this if you know what you're doing!

Furthermore, if you want to store the log file somewhere other than the logging path configured in the Joomla! settings, there is the text_file_path setting.

Logging to Other Places[edit]

As well as logging to files, you can log to other places as well, such as

  • the Joomla message area (where the message is shown if you call JFactory::getApplication()->enqueueMessage()).
  • 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. For example:

JLog::add('error copied to message bar', JLog::Error, 'jerror');

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.

PSR-3 Logger[edit]

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.

Exceptions[edit]

JLog::add() 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(
    array(
         // Use mycustomlogger.
         'logger' => 'mycustomlogger',
         'text_file' => 'com_helloworld.errors.php'
    ),
    JLog::ALL,
    array('com_helloworld')
);

Further Reading[edit]

Joomla logging should be used in tandem with PHP exceptions, not as a replacement. See J2.5:Exceptions_and_Logging_in_Joomla_Platform_11.1_and_Joomla_2.5 for backstory on this class and how it arose from the old Joomla PHP4 compatible error classes.