Skip to content
This repository has been archived by the owner on Nov 26, 2017. It is now read-only.

Commit

Permalink
Added chapter on the JLog class.
Browse files Browse the repository at this point in the history
  • Loading branch information
eddieajau committed Dec 3, 2011
1 parent f82830e commit ca7f1fe
Show file tree
Hide file tree
Showing 2 changed files with 371 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/manual/en-US/Developer_Manual.xml
Expand Up @@ -6,6 +6,7 @@
<book>
<xi:include href="Book_Info.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
<xi:include href="chapters/preface.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
<xi:include href="chapters/jlog.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
<xi:include href="chapters/github.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
<xi:include href="chapters/testing.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
<xi:include href="appendices/analysis.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
Expand Down
370 changes: 370 additions & 0 deletions docs/manual/en-US/chapters/jlog.xml
@@ -0,0 +1,370 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
<!ENTITY % BOOK_ENTITIES SYSTEM "../Developer_Manual.ent">
%BOOK_ENTITIES;
]>
<chapter id="chap-Joomla_Platform_Manual-JLog">
<title>Logging with JLog</title>

<section>
<title>Introduction</title>

<para>The Joomla Platform includes a Log package that allows for configurable, hook-driven logging to a variety of
formats.</para>

<para>The classes included in the Log package are JLog, JLogEntry, LogException, JLogger as well as the classes
JLoggerDatabase, JLoggerEcho, JLoggerFormattedText, JLoggerMessageQueue, JLoggerSyslog and JLoggerW3C which support formatting
and storage. Of all these classes, you will generally only use JLog in your projects.</para>

<para>Logging is a two-step process.</para>

<para>First you must add the add loggers to listen for log messages. Any number of loggers can be configured to listen for log
messages based on a priority and a category. For example, you can configure all log messages to be logged to the database, but
also set just errors to be logged to a file. To do this, you use the JLog::addLogger method.</para>

<para>After at least one logger is configured, you can then add messages using the JLog::addLogEntry method where you can
specify a message, and optionally a priority (integer), category (string) and date.</para>

<para></para>
</section>

<section>
<title>Logging priority</title>

<para>Before we look at any logging examples, we need to understand what the priority is. The priority is an integer mask and
is set using one or more predefined constants in the JLog class. These are: </para>

<simplelist>
<member>JLog::EMERGENCY</member>

<member>JLog::ALERT</member>

<member>JLog::CRITICAL</member>

<member>JLog::ERROR</member>

<member>JLog::WARNING</member>

<member>JLog::NOTICE</member>

<member>JLog::INFO</member>

<member>JLog::DEBUG</member>
</simplelist>

<para>A final constant, JLog::ALL is also available which corresponds to hex FFFF (16 bits). The other constants reserve the
first eight bits for system use. This allows the developer the last eight bits, hex 100 to 8000, for custom use if desired. As
the values are for masking, they can be mixed using any of the bitwise operators for <emphasis>and</emphasis>,
<emphasis>or</emphasis>, <emphasis>not</emphasis> and <emphasis>xor</emphasis>.</para>

<para>By default, loggers are added to listen for JLog::ALL priorities and log entries are added using the JLog::INFO
mask.</para>
</section>

<section>
<title>Logging to files (formattedtext)</title>

<para>A very typical example of logging is the ability to log to a file, and this is the default handler for logging. To do
this, you need to import the JLog class (if your project is based on JApplication, such as in the Joomla CMS, or JCli, the
JLog class will already be loaded), add the logger and then you can add log messages. </para>

<example>
<title>Simple log example</title>

<programlisting>// Include the JLog class.
jimport('joomla.log.log');

// Initialise a basic logger with no options (once only).
JLog::addLogger(array());

// Add a message.
JLog::add('Logged');</programlisting>
</example>

<para>As no logger has been specified in the JLog::addLogger call, the "formattedtext" logger will be used. This will log the
message to a file called "error.php" in the log folder specified by the "log_path" configuration variable (in the Joomla CMS,
the default is /logs/). It will look something like this: </para>

<example>
<title>Example of what a log file may look like</title>

<programlisting>#&lt;?php die('Forbidden.'); ?&gt;
#Date: 2011-06-17 02:56:21 UTC
#Software: Joomla Platform 11.1 Stable [ Ember ] 01-Jun-2011 06:00 GMT

#Fields: datetime priority category message
2011-06-17T03:06:44+00:00 INFO - Logged
</programlisting>
</example>

<para>The file is tab-delimited and the default columns are the timestamp, the text representation of the priority, the
category and finally the message. The category is empty (a dash) because we didn't supply it. </para>

<para>To log a different priority, you can use code like: </para>

<example>
<title>Logging with a priority</title>

<programlisting>JLog::add('Logged 3', JLog::WARNING, 'Test');</programlisting>
</example>

<para>The log file will now look similar to the following:</para>

<example>
<title>Log file with priorities</title>

<programlisting>2011-06-17T03:06:44+00:00 INFO - Logged
2011-06-17T03:52:08+00:00 WARNING - Logged 2
2011-06-17T03:57:03+00:00 WARNING test Logged 3</programlisting>
</example>

<section>
<title>Additional options with formattedtext</title>

<para>When adding the "formattedtext" logger, the following options are available to supply in the array you pass to
JLog::addLogger.</para>

<simplelist>
<member><emphasis role="bold">text_file</emphasis> - allows you to specify the name of the file to which messages are
logged.</member>

<member><emphasis role="bold">text_file_path</emphasis> - allows you to specify the folder path to the file to which
messages are logged.</member>

<member><emphasis role="bold">text_file_no_php</emphasis> - if set, the PHP die statement will not be added to the file
line of the file.</member>

<member><emphasis role="bold">text_entry_format</emphasis> - allows you to change the format of the entire line of the log
message in the file.</member>
</simplelist>
</section>

<section>
<title>Changing the name of the log file</title>

<para>Given the options outlined in the previous section, you can change the name of the file to which you are logging when
you add the logger, like this: </para>

<example>
<title>Changing the name of the log file</title>

<programlisting>// Log to a specific text file.
JLog::addLogger(
array(
'text_file' =&gt; 'mylogs.php'
)
);</programlisting>
</example>
</section>

<section>
<title>Logging different priorities to different files</title>

<para>You can log different types of messages to different files by adding multiple loggers that bind different log
priorities to different files. For example, the following code will log all messages except errors to one file, and error
messages to a separate file.</para>

<example>
<title>Logging different priorities to different files</title>

<programlisting>// Log all message except errors to mylogs.php.
JLog::addLogger(
array(
'text_file' =&gt; 'mylogs.php'
),
JLog::ALL ^ JLog::ERROR
);

// Log errors to myerrors.php.
JLog::addLogger(
array(
'text_file' =&gt; 'myerrors.php'
),
JLog::ERROR
);</programlisting>
</example>
</section>

<section>
<title>Logging specific categories to a file</title>

<para>If you are wanting to collect errors for your specific project, class or extension, you can also bind logging to
different categories. For example, the following code could be used in a Joomla extension to just collect errors relating to
it.</para>

<example>
<title>Setting up a logger for a category</title>

<programlisting>// Log my extension errors only.
JLog::addLogger(
array(
'text_file' =&gt; 'com_hello.errors.php'
),
JLog::ERROR,
'com_hello'
);</programlisting>
</example>

<para>To log messages to that logger, you would use something similar to the following code:</para>

<example>
<title>Logging to a category</title>

<programlisting>JLog::add('Forgot to say goodbye', JLog::ERROR, 'com_hello');</programlisting>
</example>

<para>It is important to note that other loggers, added beyond your control, may also pick up this message.</para>
</section>

<section>
<title>Splitting up logs by date</title>

<para>Log files can, potentially, get very long over time. A convenient solution to this is to roll logs into different
files based on a period of time - an hour, a day, a month or even a year. To do this, you just need to add the date to the
file name of the log file. The following example shows you how to do this on a daily basis. </para>

<example>
<title>Splitting log files by date</title>

<programlisting>// Get the date.
$date = JFactory::getDate()-&gt;format('Y-m-d');

// Add the logger.
JLog::addLogger(
array(
'text_file' =&gt; 'com_hello.'.$date.'.php'
)
);</programlisting>
</example>
</section>

<section>
<title>Changing the format of the log message</title>

<para>When you adding a log message, it is written to the file in a default format in the form: </para>

<example>
<title>Default log file format</title>

<programlisting>{DATETIME} {PRIORITY} {CATEGORY} {MESSAGE}</programlisting>
</example>

<para>Each field is written in upper case, wrapped in curly braces and separated by tabs. There are a number of other fields
that are automatically defined in the "formattedtext" logger that you can take advantage of automatically. These are:
</para>

<simplelist>
<member>{CLIENTIP} - the IP address of the user.</member>

<member>{DATE} - the "Y-m-d" date component of the message datestamp.</member>

<member>{TIME} - the "H:i:s" time component of the message datestamp.</member>
</simplelist>

<para>To modify for the log format to add any or all of these fields, you can add the logger as shown in the following
code.</para>

<example>
<title>Customizing the log file format</title>

<programlisting>// Add the logger.
JLog::addLogger(
array(
'text_file' =&gt; 'com_hello.php',
'text_entry_format' =&gt; '{DATE} {TIME} {CLIENTIP} {CATEGORY} {MESSAGE}'
)
);</programlisting>
</example>

<para>As you can see, you can include or leave out any fields as you require to suit the needs of your project.</para>

<para>You can also add more fields but to do this you need to create and add a JLogEntry object directly. The following
example shows you how to do this.</para>

<example>
<title>Adding custom fields to a log entry</title>

<programlisting>// Add the logger.
JLog::addLogger(
array(
'text_file' =&gt; 'com_shop.sales.php',
'text_entry_format' =&gt; '{DATETIME} {PRICE} {QUANTITY} {MESSAGE}'
),
JLog::INFO,
'Shop'
);

$logEntry = new JLogEntry('T- Shirt', JLog::INFO, 'Shop');
$logEntry-&gt;price = '7.99';
$logEntry-&gt;quantity = 10;

JLog::add($logEntry);</programlisting>
</example>

<para>It is strongly recommended that, when using a custom format, you bind the log entries to a specific and unique
category, otherwise log files with different format (columns) could become mixed.</para>
</section>
</section>

<section>
<title>Logging to the database </title>

<para>The "database" logger allows you to log message to a database table. The create syntax for the default table is as
follows: </para>

<example>
<title>Example schema for a database logger</title>

<programlisting>CREATE TABLE `jos_log_entries` (
`priority` int(11) DEFAULT NULL,
`message` varchar(512) DEFAULT NULL,
`date` datetime DEFAULT NULL,
`category` varchar(255) DEFAULT NULL,
KEY `idx_category_date_priority` (`category`,`date`,`priority`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;</programlisting>
</example>

<para>To log messages using the "database" logger, you the following code as a guide.</para>

<example>
<title>Using a database logger</title>

<programlisting>// Add the logger.
JLog::addLogger(
array(
'logger' =&gt; 'database'
),
JLog::ALL,
'dblog'
);

// Add the message.
JLog::add('Database log', JLog::INFO, 'dblog');</programlisting>
</example>

<para>Notice that the example binds the logger to all message priorities, but only those with a category of "dblog". </para>

<para>If you are wanting to store additional information in the message, you can do so using a JSON encoded string. For
example:</para>

<example>
<title>Storing variable information in a log message</title>

<programlisting>// Assemble the log message.
$user = JFactory::getUser();
$log = array(
'userId' =&gt; $user-&gt;get('id'),
'userName' =&gt; $user-&gt;get('name'),
'stockId' =&gt; 'SKU123',
'price' =&gt; '7.49',
'quantity' =&gt; 10
);

// Add the message.
JLog::add(json_encode($log), JLog::INFO, 'dblog');</programlisting>
</example>

<para>This makes it possible to retrieve detailed information for display.</para>
</section>
</chapter>

0 comments on commit ca7f1fe

Please sign in to comment.