MongoDbTarget.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\mongodb\log;
  8. use yii\base\InvalidConfigException;
  9. use yii\di\Instance;
  10. use yii\helpers\VarDumper;
  11. use yii\log\Target;
  12. use yii\mongodb\Connection;
  13. /**
  14. * MongoDbTarget stores log messages in a MongoDB collection.
  15. *
  16. * By default, MongoDbTarget stores the log messages in a MongoDB collection named 'log'.
  17. * The collection can be changed by setting the [[logCollection]] property.
  18. *
  19. * @author Paul Klimov <klimov.paul@gmail.com>
  20. * @since 2.0
  21. */
  22. class MongoDbTarget extends Target
  23. {
  24. /**
  25. * @var Connection|string the MongoDB connection object or the application component ID of the MongoDB connection.
  26. * After the MongoDbTarget object is created, if you want to change this property, you should only assign it
  27. * with a MongoDB connection object.
  28. */
  29. public $db = 'mongodb';
  30. /**
  31. * @var string|array the name of the MongoDB collection that stores the session data.
  32. * Please refer to [[Connection::getCollection()]] on how to specify this parameter.
  33. * This collection is better to be pre-created with fields 'id' and 'expire' indexed.
  34. */
  35. public $logCollection = 'log';
  36. /**
  37. * Initializes the MongoDbTarget component.
  38. * This method will initialize the [[db]] property to make sure it refers to a valid MongoDB connection.
  39. * @throws InvalidConfigException if [[db]] is invalid.
  40. */
  41. public function init()
  42. {
  43. parent::init();
  44. $this->db = Instance::ensure($this->db, Connection::className());
  45. }
  46. /**
  47. * Stores log messages to MongoDB collection.
  48. */
  49. public function export()
  50. {
  51. $rows = [];
  52. foreach ($this->messages as $message) {
  53. list($text, $level, $category, $timestamp) = $message;
  54. if (!is_string($text)) {
  55. // exceptions may not be serializable if in the call stack somewhere is a Closure
  56. if ($text instanceof \Throwable || $text instanceof \Exception) {
  57. $text = (string) $text;
  58. } else {
  59. $text = VarDumper::export($text);
  60. }
  61. }
  62. $rows[] = [
  63. 'level' => $level,
  64. 'category' => $category,
  65. 'log_time' => $timestamp,
  66. 'prefix' => $this->getMessagePrefix($message),
  67. 'message' => $text,
  68. ];
  69. }
  70. $this->db->getCollection($this->logCollection)->batchInsert($rows);
  71. }
  72. }