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