PageRenderTime 40ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/bower_components/joomla-platform/docs/manual/en-US/chapters/packages/log.md

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