PageRenderTime 59ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/documentation/08-logging.markdown

https://github.com/stood/propelorm.github.com
Markdown | 439 lines | 345 code | 94 blank | 0 comment | 0 complexity | bfcbed14a436dcf187dcac46d435adfd MD5 | raw file
  1. ---
  2. layout: documentation
  3. title: Logging And Debugging
  4. ---
  5. # Logging And Debugging #
  6. Propel provides tools to monitor and debug your model. Whether you need to check the SQL code of slow queries, or to look for error messages previously thrown, Propel is your best friend for finding and fixing problems.
  7. ## Propel Logs ##
  8. Propel uses the logging facility configured in `runtime-conf.xml` to record errors, warnings, and debug information.
  9. By default Propel will attempt to use the Log framework that is distributed with PEAR. If you are not familiar with it, check its [online documentation](http://www.indelible.org/php/Log/guide.html). It is also easy to configure Propel to use your own logging framework -- or none at all.
  10. >**Tip**<br />Install PEAR Log using `pear install Log`
  11. ### Logger Configuration ###
  12. The Propel log handler is configured in the `<log>` section of your project's `runtime-conf.xml` file. Here is the accepted format for this section with the default values that Propel uses:
  13. ```xml
  14. <?xml version="1.0" encoding="ISO-8859-1"?>
  15. <config>
  16. <log>
  17. <type>file</type>
  18. <name>./propel.log</name>
  19. <ident>propel</ident>
  20. <level>7</level> <!-- PEAR_LOG_DEBUG -->
  21. <conf></conf>
  22. </log>
  23. <propel>
  24. ...
  25. </propel>
  26. </config>
  27. ```
  28. >**Tip**<br />Remember to run `propel-gen convert-conf` after modifying the configuration files.
  29. Using these parameters, Propel creates a `file` Log handler in the background, and keeps it for later use:
  30. ```php
  31. <?php
  32. Propel::setLogger(Log::singleton($type = 'file', $name = './propel.log', $ident = 'propel', $conf = array(), $level = PEAR_LOG_DEBUG));
  33. ```
  34. The meaning of each of the `<log>` nested elements may vary, depending on which log handler you are using. Most common accepted logger types are `file`, `console`, `syslog`, `display`, `error_log`, `firebug`, and `sqlite`. Refer to the [PEAR::Log](http://www.indelible.org/php/Log/guide.html#standard-log-handlers) documentation for more details on log handlers configuration and options.
  35. Note that the `<level>` tag needs to correspond to the integer represented by one of the `PEAR_LOG_*` constants:
  36. |Constant |Value |Description
  37. |-------------------|-------|-------------------------
  38. |PEAR_LOG_EMERG |0 |System is unusable
  39. |PEAR_LOG_ALERT |1 |Immediate action required
  40. |PEAR_LOG_CRIT |2 |Critical conditions
  41. |PEAR_LOG_ERR |3 |Error conditions
  42. |PEAR_LOG_WARNING |4 |Warning conditions
  43. |PEAR_LOG_NOTICE |5 |Normal but significant
  44. |PEAR_LOG_INFO |6 |Informational
  45. |PEAR_LOG_DEBUG |7 |Debug-level messages
  46. ### Logging Messages ###
  47. Use the static `Propel::log()` method to log a message using the configured log handler:
  48. ```php
  49. <?php
  50. $myObj = new MyObj();
  51. $myObj->setName('foo');
  52. Propel::log('uh-oh, something went wrong with ' . $myObj->getName(), Propel::LOG_ERR);
  53. ```
  54. You can log your own messages from the generated model objects by using their `log()` method, inherited from `BaseObject`:
  55. ```php
  56. <?php
  57. $myObj = new MyObj();
  58. $myObj->log('uh-oh, something went wrong', Propel::LOG_ERR);
  59. ```
  60. The log messages will show up in the log handler defined in `runtime-conf.xml` (`propel.log` file by default) as follows:
  61. ```text
  62. Oct 04 00:00:18 [error] uh-oh, something went wrong with foo
  63. Oct 04 00:00:18 [error] MyObj: uh-oh, something went wrong
  64. ```
  65. >**Tip**<br />All serious errors coming from the Propel core do not only issue a log message, they are also thrown as `PropelException`.
  66. ### Using An Alternative PEAR Log Handler ###
  67. In many cases you may wish to integrate Propel's logging facility with the rest of your web application. In `runtime-conf.xml`, you can customize a different PEAR logger. Here are a few examples:
  68. _Example 1:_ Using `display` handler (for output to HTML)
  69. ```xml
  70. <log>
  71. <type>display</type>
  72. <level>6</level> <!-- PEAR_LOG_INFO -->
  73. </log>
  74. ```
  75. _Example 2:_ Using `syslog` handler
  76. ```xml
  77. <log>
  78. <type>syslog</type>
  79. <name>8</name> <!-- LOG_USER -->
  80. <ident>propel</ident>
  81. <level>6</level>
  82. </log>
  83. ```
  84. ### Using A Custom Logger ###
  85. If you omit the `<log>` section of your `runtime-conf.xml`, then Propel will not setup _any_ logging for you. In this case, you can set a custom logging facility and pass it to Propel at runtime.
  86. Here's an example of how you could configure your own logger and then set Propel to use it:
  87. ```php
  88. <?php
  89. require_once 'MyLogger.php';
  90. $logger = new MyLogger();
  91. require_once 'propel/Propel.php';
  92. Propel::setLogger($logger);
  93. Propel::init('/path/to/runtime-conf.php');
  94. ```
  95. Your custom logger could be any object that implements a basic logger interface. Check the `BasicLogger` interface provided with the Propel runtime to see the methods that a logger must implement in order to be compatible with Propel. You do not actually have to implement this interface, but all the specified methods must be present in your container.
  96. Let's see an example of a simple log container suitable for use with Propel:
  97. ```php
  98. <?php
  99. class MyLogger implements BasicLogger
  100. {
  101. public function emergency($m)
  102. {
  103. $this->log($m, Propel::LOG_EMERG);
  104. }
  105. public function alert($m)
  106. {
  107. $this->log($m, Propel::LOG_ALERT);
  108. }
  109. public function crit($m)
  110. {
  111. $this->log($m, Propel::LOG_CRIT);
  112. }
  113. public function err($m)
  114. {
  115. $this->log($m, Propel::LOG_ERR);
  116. }
  117. public function warning($m)
  118. {
  119. $this->log($m, Propel::LOG_WARNING);
  120. }
  121. public function notice($m)
  122. {
  123. $this->log($m, Propel::LOG_NOTICE);
  124. }
  125. public function info($m)
  126. {
  127. $this->log($m, Propel::LOG_INFO);
  128. }
  129. public function debug($m)
  130. {
  131. $this->log($m, Propel::LOG_DEBUG);
  132. }
  133. public function log($message, $priority)
  134. {
  135. $color = $this->priorityToColor($priority);
  136. echo '<p style="color: ' . $color . '">' . $message . '</p>';
  137. }
  138. private function priorityToColor($priority)
  139. {
  140. switch($priority) {
  141. case Propel::LOG_EMERG:
  142. case Propel::LOG_ALERT:
  143. case Propel::LOG_CRIT:
  144. case Propel::LOG_ERR:
  145. return 'red';
  146. break;
  147. case Propel::LOG_WARNING:
  148. return 'orange';
  149. break;
  150. case Propel::LOG_NOTICE:
  151. return 'green';
  152. break;
  153. case Propel::LOG_INFO:
  154. return 'blue';
  155. break;
  156. case Propel::LOG_DEBUG:
  157. return 'grey';
  158. break;
  159. }
  160. }
  161. }
  162. ```
  163. >**Tip**<br />There is also a bundled `MojaviLogAdapter` class which allows you to use a Mojavi logger with Propel.
  164. ## Debugging Database Activity ##
  165. By default, Propel uses `PropelPDO` for database connections. This class, which extends PHP's `PDO`, offers a debug mode to keep track of all the database activity, including all the executed queries.
  166. ### Enabling The Debug Mode ###
  167. The debug mode is disabled by default, but you can enable it at runtime as follows:
  168. ```php
  169. <?php
  170. $con = Propel::getConnection(MyObjPeer::DATABASE_NAME);
  171. $con->useDebug(true);
  172. ```
  173. You can also disable the debug mode at runtime, by calling `PropelPDO::useDebug(false)`. Using this method, you can choose to enable the debug mode for only one particular query, or for all queries.
  174. Alternatively, you can ask Propel to always enable the debug mode for a particular connection by using the `DebugPDO` class instead of the default `PropelPDO` class. This is accomplished in the `runtime-conf.xml` file, in the `<classname>` tag of a given datasource connection (see the [runtime configuration reference]() for more details).
  175. ```xml
  176. <?xml version="1.0"?>
  177. <config>
  178. <propel>
  179. <datasources default="bookstore">
  180. <datasource id="bookstore">
  181. <adapter>sqlite</adapter>
  182. <connection>
  183. <!-- the classname that Propel should instantiate, must be PropelPDO subclass -->
  184. <classname>DebugPDO</classname>
  185. ```
  186. >**Tip**<br />You can use your own connection class there, but make sure that it extends `PropelPDO` and not only `PDO`. Propel requires certain fixes to PDO API that are provided by `PropelPDO`.
  187. ### Counting Queries ###
  188. In debug mode, `PropelPDO` keeps track of the number of queries that are executed. Use `PropelPDO::getQueryCount()` to retrieve this number:
  189. ```php
  190. <?php
  191. $con = Propel::getConnection(MyObjPeer::DATABASE_NAME);
  192. $myObjs = MyObjPeer::doSelect(new Criteria(), $con);
  193. echo $con->getQueryCount(); // 1
  194. ```
  195. Tip: You cannot use persistent connections if you want the query count to work. Actually, the debug mode in general requires that you don't use persistent connections in order for it to correctly log bound values and count executed statements.
  196. ### Retrieving The Latest Executed Query ###
  197. For debugging purposes, you may need the SQL code of the latest executed query. It is available at runtime in debug mode using `PropelPDO::getLastExecutedQuery()`, as follows:
  198. ```php
  199. <?php
  200. $con = Propel::getConnection(MyObjPeer::DATABASE_NAME);
  201. $myObjs = MyObjPeer::doSelect(new Criteria(), $con);
  202. echo $con->getLastExecutedQuery(); // 'SELECT * FROM my_obj';
  203. ```
  204. Tip: You can also get a decent SQL representation of the criteria being used in a SELECT query by using the `Criteria->toString()` method.
  205. Propel also keeps track of the queries executed directly on the connection object, and displays the bound values correctly.
  206. ```php
  207. <?php
  208. $con = Propel::getConnection(MyObjPeer::DATABASE_NAME);
  209. $stmt = $con->prepare('SELECT * FROM my_obj WHERE name = :p1');
  210. $stmt->bindValue(':p1', 'foo');
  211. $stmt->execute();
  212. echo $con->getLastExecutedQuery(); // 'SELECT * FROM my_obj where name = "foo"';
  213. ```
  214. >**Tip**<br />The debug mode is intended for development use only. Do not use it in production environment, it logs too much information for a production server, and adds a small overhead to the database queries.
  215. ## Full Query Logging ##
  216. The combination of the debug mode and a logging facility provides a powerful debugging tool named _full query logging_. If you have properly configured a log handler, enabling the debug mode (or using `DebugPDO`) automatically logs the executed queries into Propel's default log file:
  217. ```text
  218. Oct 04 00:00:18 propel-bookstore [debug] INSERT INTO publisher (`ID`,`NAME`) VALUES (NULL,'William Morrow')
  219. Oct 04 00:00:18 propel-bookstore [debug] INSERT INTO author (`ID`,`FIRST_NAME`,`LAST_NAME`) VALUES (NULL,'J.K.','Rowling')
  220. Oct 04 00:00:18 propel-bookstore [debug] INSERT INTO book (`ID`,`TITLE`,`ISBN`,`PRICE`,`PUBLISHER_ID`,`AUTHOR_ID`) VALUES (NULL,'Harry Potter and the Order of the Phoenix','043935806X',10.99,53,58)
  221. Oct 04 00:00:18 propel-bookstore [debug] INSERT INTO review (`ID`,`REVIEWED_BY`,`REVIEW_DATE`,`RECOMMENDED`,`BOOK_ID`) VALUES (NULL,'Washington Post','2009-10-04',1,52)
  222. ...
  223. Oct 04 00:00:18 propel-bookstore [debug] SELECT bookstore_employee_account.EMPLOYEE_ID, bookstore_employee_account.LOGIN FROM `bookstore_employee_account` WHERE bookstore_employee_account.EMPLOYEE_ID=25
  224. ```
  225. By default, Propel logs all SQL queries, together with the date of the query and the name of the connection.
  226. ### Setting The Data To Log ###
  227. The full query logging feature can be configured either in the `runtime-conf.xml` configuration file, or using the runtime configuration API.
  228. In `runtime-conf.xml`, tweak the feature by adding a `<debugpdo>` tag under `<propel>`:
  229. ```xml
  230. <?xml version="1.0"?>
  231. <config>
  232. <log>
  233. ...
  234. </log>
  235. <propel>
  236. <datasources default="bookstore">
  237. ...
  238. </datasources>
  239. <debugpdo>
  240. <logging>
  241. <details>
  242. <method>
  243. <enabled>true</enabled>
  244. </method>
  245. <time>
  246. <enabled>true</enabled>
  247. </time>
  248. <mem>
  249. <enabled>true</enabled>
  250. </mem>
  251. </details>
  252. </logging>
  253. </debugpdo>
  254. </propel>
  255. </config>
  256. ```
  257. To accomplish the same configuration as above at runtime, change the settings in your main include file, after `Propel::init()`, as follows:
  258. ```php
  259. <?php
  260. $config = Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT);
  261. $config->setParameter('debugpdo.logging.details.method.enabled', true);
  262. $config->setParameter('debugpdo.logging.details.time.enabled', true);
  263. $config->setParameter('debugpdo.logging.details.mem.enabled', true);
  264. ```
  265. Let's see a few of the provided parameters.
  266. ### Logging More Connection Messages ###
  267. `PropelPDO` can log queries, but also connection events (open and close), and transaction events (begin, commit and rollback). Since Propel can emulate nested transactions, you may need to know when an actual `COMMIT` or `ROLLBACK` is issued.
  268. To extend which methods of `PropelPDO` do log messages in debug mode, customize the `'debugpdo.logging.methods'` parameter, as follows:
  269. ```php
  270. <?php
  271. $allMethods = array(
  272. 'PropelPDO::__construct', // logs connection opening
  273. 'PropelPDO::__destruct', // logs connection close
  274. 'PropelPDO::exec', // logs a query
  275. 'PropelPDO::query', // logs a query
  276. 'PropelPDO::prepare', // logs the preparation of a statement
  277. 'PropelPDO::beginTransaction', // logs a transaction begin
  278. 'PropelPDO::commit', // logs a transaction commit
  279. 'PropelPDO::rollBack', // logs a transaction rollBack (watch out for the capital 'B')
  280. 'DebugPDOStatement::execute', // logs a query from a prepared statement
  281. 'DebugPDOStatement::bindValue' // logs the value and type for each bind
  282. );
  283. $config = Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT);
  284. $config->setParameter('debugpdo.logging.methods', $allMethods, false);
  285. ```
  286. By default, only the messages coming from `PropelPDO::exec`, `PropelPDO::query`, and `DebugPDOStatement::execute` are logged.
  287. ### Logging Execution Time And Memory ###
  288. In debug mode, Propel counts the time and memory necessary for each database query. This very valuable data can be added to the log messages on demand, by adding the following configuration:
  289. ```php
  290. <?php
  291. $config = Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT);
  292. $config->setParameter('debugpdo.logging.details.time.enabled', true);
  293. $config->setParameter('debugpdo.logging.details.mem.enabled', true);
  294. ```
  295. Enabling the options shown above, you get log output along the lines of:
  296. ```text
  297. Feb 23 16:41:04 Propel [debug] time: 0.000 sec | mem: 1.4 MB | SET NAMES 'utf8'
  298. Feb 23 16:41:04 Propel [debug] time: 0.002 sec | mem: 1.6 MB | SELECT COUNT(tags.NAME) FROM tags WHERE tags.IMAGEID = 12
  299. Feb 23 16:41:04 Propel [debug] time: 0.012 sec | mem: 2.4 MB | SELECT tags.NAME, image.FILENAME FROM tags LEFT JOIN image ON tags.IMAGEID = image.ID WHERE image.ID = 12
  300. ```
  301. The order in which the logging details are enabled is significant, since it determines the order in which they will appear in the log file.
  302. ### Complete List Of Logging Options ###
  303. The following settings can be customized at runtime or in the configuration file:
  304. |Parameter |Default |Meaning
  305. |-----------------------------------------------|-----------|---------------------------------------------------------------------------------
  306. |`debugpdo.logging.innerglue` |":" |String to use for combining the title of a detail and its value
  307. |`debugpdo.logging.outerglue` |"&#124;" |String to use for combining details together on a log line
  308. |`debugpdo.logging.realmemoryusage` |`false` |Parameter to [memory_get_usage()](http://www.php.net/manual/en/function.memory-get-usage.php) and [memory_get_peak_usage()](http://www.php.net/manual/en/function.memory-get-peak-usage.php) calls
  309. |`debugpdo.logging.methods` |`array` |An array of method names (`Class::method`) to be included in method call logging
  310. |`debugpdo.logging.details.slow.enabled` |`false` |Enables flagging of slow method calls
  311. |`debugpdo.logging.details.slow.threshold` |`0.1` |Method calls taking more seconds than this threshold are considered slow
  312. |`debugpdo.logging.details.time.enabled` |`false` |Enables logging of method execution times
  313. |`debugpdo.logging.details.time.precision` |`3` |Determines the precision of the execution time logging
  314. |`debugpdo.logging.details.time.pad` |`10` |How much horizontal space to reserve for the execution time on a log line
  315. |`debugpdo.logging.details.mem.enabled` |`false` |Enables logging of the instantaneous PHP memory consumption
  316. |`debugpdo.logging.details.mem.precision` |`1` |Determines the precision of the memory consumption logging
  317. |`debugpdo.logging.details.mem.pad` |`9` |How much horizontal space to reserve for the memory consumption on a log line
  318. |`debugpdo.logging.details.memdelta.enabled` |`false` |Enables logging differences in memory consumption before and after the method call
  319. |`debugpdo.logging.details.memdelta.precision` |`1` |Determines the precision of the memory difference logging
  320. |`debugpdo.logging.details.memdelta.pad` |`10` |How much horizontal space to reserve for the memory difference on a log line
  321. |`debugpdo.logging.details.mempeak.enabled` |`false` |Enables logging the peak memory consumption thus far by the currently executing PHP script
  322. |`debugpdo.logging.details.mempeak.precision` |`1` |Determines the precision of the memory peak logging
  323. |`debugpdo.logging.details.mempeak.pad` |`9` |How much horizontal space to reserve for the memory peak on a log line
  324. |`debugpdo.logging.details.querycount.enabled` |`false` |Enables logging of the number of queries performed by the DebugPDO instance thus far
  325. |`debugpdo.logging.details.querycount.pad` |`2` |How much horizontal space to reserve for the query count on a log line
  326. |`debugpdo.logging.details.method.enabled` |`false` |Enables logging of the name of the method call
  327. |`debugpdo.logging.details.method.pad` |`28` |How much horizontal space to reserve for the method name on a log line
  328. ### Changing the Log Level ###
  329. By default the connection log messages are logged at the `Propel::LOG_DEBUG` level. This can be changed by calling the `setLogLevel()` method on the connection object:
  330. ```php
  331. <?php
  332. $con = Propel::getConnection(MyObjPeer::DATABASE_NAME);
  333. $con->setLogLevel(Propel::LOG_INFO);
  334. ```
  335. Now all queries and bind param values will be logged at the INFO level.
  336. ### Configuring a Different Full Query Logger ###
  337. By default the `PropelPDO` connection logs queries and binds param values using the `Propel::log()` static method. As explained above, this method uses the log storage configured by the `<log>` tag in the `runtime-conf.xml` file.
  338. If you would like the queries to be logged using a different logger (e.g. to a different file, or with different ident, etc.), you can set a logger explicitly on the connection at runtime, using `Propel::setLogger()`:
  339. ```php
  340. <?php
  341. $con = Propel::getConnection(MyObjPeer::DATABASE_NAME);
  342. $logger = Log::factory('syslog', LOG_LOCAL0, 'propel', array(), PEAR_LOG_INFO);
  343. $con->setLogger($logger);
  344. ```
  345. This will not affect the general Propel logging, but only the full query logging. That way you can log the Propel error and warnings in one file, and the SQL queries in another file.