PageRenderTime 31ms CodeModel.GetById 14ms app.highlight 14ms RepoModel.GetById 1ms app.codeStats 0ms

/src/Joomla/Log/README.md

https://github.com/dianaprajescu/joomla-framework
Markdown | 312 lines | 243 code | 69 blank | 0 comment | 0 complexity | 3a235217110cebe1ad0c71617008e5f9 MD5 | raw file
  1## The Log Package
  2
  3### Introduction
  4
  5The Joomla Framework includes a Log package that allows for configurable,
  6hook-driven logging to a variety of formats.
  7
  8The classes included in the Log package are `JLog`, `JLogEntry`,
  9`JLogger` as well as the classes `JLoggerDatabase`,
 10`JLoggerEcho`, `JLoggerFormattedText`, `JLoggerMessageQueue`, `JLoggerSyslog`
 11and `JLoggerW3C` which support formatting and storage. Of all these
 12classes, you will generally only use `JLog` in your projects.
 13
 14Logging is a two-step process.
 15
 16First you must add the add loggers to listen for log messages. Any
 17number of loggers can be configured to listen for log messages based on
 18a priority and a category. For example, you can configure all log
 19messages to be logged to the database, but also set just errors to be
 20logged to a file. To do this, you use the `JLog::addLogger` method.
 21
 22After at least one logger is configured, you can then add messages using
 23the `JLog::addLogEntry` method where you can specify a message, and
 24optionally a priority (integer), category (string) and date.
 25
 26### Logging priority
 27
 28Before we look at any logging examples, we need to understand what the
 29priority is. The priority is an integer mask and is set using one or
 30more predefined constants in the `JLog` class. These are:
 31
 32* JLog::EMERGENCY
 33* JLog::ALERT
 34* JLog::CRITICAL
 35* JLog::ERROR
 36* JLog::WARNING
 37* JLog::NOTICE
 38* JLog::INFO
 39* JLog::DEBUG
 40
 41For information on what situation to use each constant in see the PSR-3
 42(Section 3) details here - https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md#3-psrlogloggerinterface
 43where a detailed explanation can be found.
 44
 45
 46A final constant, `JLog::ALL` is also available which corresponds to hex
 47FFFF (16 bits). The other constants reserve the first eight bits for
 48system use. This allows the developer the last eight bits, hex 100 to
 498000, for custom use if desired. As the values are for masking, they can
 50be mixed using any of the bitwise operators for *and*, *or*, *not* and
 51*xor*.
 52
 53By default, loggers are added to listen for `JLog::ALL` priorities and log
 54entries are added using the `JLog::INFO` mask.
 55
 56### Logging to files *(formattedtext)*
 57
 58A very typical example of logging is the ability to log to a file, and
 59this is the default handler for logging. To do this add the
 60logger and then you can add log messages.
 61
 62```php
 63// Initialise a basic logger with no options (once only).
 64JLog::addLogger(array());
 65
 66// Add a message.
 67JLog::add('Logged');
 68```
 69
 70As no logger has been specified in the `JLog::addLogger` call, the
 71"formattedtext" logger will be used. This will log the message to a file
 72called "error.php" in the log folder specified by the "log_path"
 73configuration variable (in the Joomla CMS, the default is `/logs/`). It
 74will look something like this:
 75
 76    #<?php die('Forbidden.'); ?>
 77    #Date: 2011-06-17 02:56:21 UTC
 78    #Software: Joomla Framework 01-Jun-2011 06:00 GMT
 79
 80    #Fields: datetime   priority    category    message
 81    2011-06-17T03:06:44+00:00   INFO    -   Logged
 82
 83The file is tab-delimited and the default columns are the timestamp, the
 84text representation of the priority, the category and finally the
 85message. The category is empty (a dash) because we didn't supply it.
 86
 87To log a different priority, you can use code like:
 88
 89```php
 90JLog::add('Logged 3', JLog::WARNING, 'Test');
 91```
 92
 93The log file will now look similar to the following:
 94
 95    2011-06-17T03:06:44+00:00 INFO - Logged
 96    2011-06-17T03:52:08+00:00 WARNING - Logged 2
 97    2011-06-17T03:57:03+00:00 WARNING test Logged 3
 98
 99#### Additional options with formattedtext
100
101When adding the "formattedtext" logger, the following options are
102available to supply in the array you pass to `JLog::addLogger`.
103
104Option              | Description
105------------------- | ----------------
106text\_file          | Allows you to specify the name of the file to which messages are logged.
107text\_file\_path    | Allows you to specify the folder path to the file to which messages are logged.
108text\_file\_no\_php | If set, the PHP die statement will not be added to the file line of the file.
109text\_entry\_format | Allows you to change the format of the entire line of the log message in the file.
110
111### Changing the name of the log file
112
113Given the options outlined in the previous section, you can change the
114name of the file to which you are logging when you add the logger, like
115this:
116
117```php
118// Log to a specific text file.
119JLog::addLogger(
120	array(
121		'text_file' => 'mylogs.php'
122	)
123);
124```
125
126#### Logging different priorities to different files
127
128You can log different types of messages to different files by adding
129multiple loggers that bind different log priorities to different files.
130For example, the following code will log all messages except errors to
131one file, and error messages to a separate file.
132
133```php
134// Log all message except errors to mylogs.php.
135JLog::addLogger(
136	array(
137		'text_file' => 'mylogs.php'
138	),
139	JLog::ALL ^ JLog::ERROR
140);
141
142// Log errors to myerrors.php.
143JLog::addLogger(
144	array(
145		'text_file' => 'myerrors.php'
146	),
147	JLog::ERROR
148);
149```
150
151#### Logging specific categories to a file
152
153If you are wanting to collect errors for your specific project, class or
154extension, you can also bind logging to different categories. For
155example, the following code could be used in a Joomla extension to just
156collect errors relating to it.
157
158```php
159// Log my extension errors only.
160JLog::addLogger(
161	array(
162		'text_file' => 'com_hello.errors.php'
163	),
164	JLog::ERROR,
165	'com_hello'
166);
167```
168
169To log messages to that logger, you would use something similar to the
170following code:
171
172```php
173JLog::add('Forgot to say goodbye', JLog::ERROR, 'com_hello');
174```
175
176It is important to note that other loggers, added beyond your control,
177may also pick up this message.
178
179#### Splitting up logs by date
180
181Log files can, potentially, get very long over time. A convenient
182solution to this is to roll logs into different files based on a period
183of time - an hour, a day, a month or even a year. To do this, you just
184need to add the date to the file name of the log file. The following
185example shows you how to do this on a daily basis.
186
187```php
188// Get the date.
189$date = JFactory::getDate()->format('Y-m-d');
190
191// Add the logger.
192JLog::addLogger(
193	array(
194		'text_file' => 'com_hello.'.$date.'.php'
195	)
196);
197```
198
199#### Changing the format of the log message
200
201When you adding a log message, it is written to the file in a default
202format in the form:
203
204    {DATETIME} {PRIORITY} {CATEGORY} {MESSAGE}
205
206Each field is written in upper case, wrapped in curly braces and
207separated by tabs. There are a number of other fields that are
208automatically defined in the "formattedtext" logger that you can take
209advantage of automatically. These are:
210
211Field      | Description
212---------- | -----------
213{CLIENTIP} | The IP address of the user.
214{DATE}     | The "Y-m-d" date component of the message datestamp.
215{TIME}     | The "H:i:s" time component of the message datestamp.
216
217To modify for the log format to add any or all of these fields, you can
218add the logger as shown in the following code.
219
220```php
221// Add the logger.
222JLog::addLogger(
223	array(
224		'text_file' => 'com_hello.php',
225		'text_entry_format' => '{DATE} {TIME} {CLIENTIP} {CATEGORY} {MESSAGE}' 
226	)
227);
228```
229
230As you can see, you can include or leave out any fields as you require
231to suit the needs of your project.
232
233You can also add more fields but to do this you need to create and add a
234`JLogEntry` object directly. The following example shows you how to do
235this.
236
237```php
238// Add the logger.
239JLog::addLogger(
240	array(
241		'text_file' => 'com_shop.sales.php',
242		'text_entry_format' => '{DATETIME} {PRICE} {QUANTITY} {MESSAGE}'
243	),
244	JLog::INFO,
245	'Shop'
246);
247
248$logEntry = new JLogEntry('T- Shirt', JLog::INFO, 'Shop');
249$logEntry->price = '7.99';
250$logEntry->quantity = 10;
251
252JLog::add($logEntry);
253```
254
255It is strongly recommended that, when using a custom format, you bind
256the log entries to a specific and unique category, otherwise log files
257with different format *(fields)* could become mixed.
258
259### Logging to the database
260
261The "database" logger allows you to log message to a database table. The
262create syntax for the default table is as follows:
263
264```sql
265CREATE TABLE `jos_log_entries` (
266	`priority` int(11) DEFAULT NULL,
267	`message` varchar(512) DEFAULT NULL,
268	`date` datetime DEFAULT NULL,
269	`category` varchar(255) DEFAULT NULL,
270	KEY `idx_category_date_priority` (`category`,`date`,`priority`)
271) ENGINE=InnoDB DEFAULT CHARSET=utf8;
272```
273
274To log messages using the "database" logger, you the following code as a
275guide.
276
277```php
278// Add the logger.
279JLog::addLogger(
280	array(
281		'logger' => 'database'
282	),
283	JLog::ALL,
284	'dblog'
285);
286
287// Add the message.
288JLog::add('Database log', JLog::INFO, 'dblog');
289```
290
291Notice that the example binds the logger to all message priorities, but
292only those with a category of "dblog".
293
294If you are wanting to store additional information in the message, you
295can do so using a JSON encoded string. For example:
296
297```php
298// Assemble the log message.
299$user = JFactory::getUser();
300$log = array(
301	'userId' => $user->get('id'),
302	'userName' => $user->get('name'),
303	'stockId' => 'SKU123',
304	'price' => '7.49',
305	'quantity' => 10
306);
307
308// Add the message.
309JLog::add(json_encode($log), JLog::INFO, 'dblog');
310```
311
312This makes it possible to retrieve detailed information for display.