Writer.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * Log writer abstract class. All [Log] writers must extend this class.
  4. *
  5. * @package Kohana
  6. * @category Logging
  7. * @author Kohana Team
  8. * @copyright (c) Kohana Team
  9. * @license https://koseven.ga/LICENSE.md
  10. */
  11. abstract class Kohana_Log_Writer {
  12. /**
  13. * @var string timestamp format for log entries.
  14. *
  15. * Defaults to Date::$timestamp_format
  16. */
  17. public static $timestamp;
  18. /**
  19. * @var string timezone for log entries
  20. *
  21. * Defaults to Date::$timezone, which defaults to date_default_timezone_get()
  22. */
  23. public static $timezone;
  24. /**
  25. * Numeric log level to string lookup table.
  26. * @var array
  27. */
  28. protected $_log_levels = [
  29. LOG_EMERG => 'EMERGENCY',
  30. LOG_ALERT => 'ALERT',
  31. LOG_CRIT => 'CRITICAL',
  32. LOG_ERR => 'ERROR',
  33. LOG_WARNING => 'WARNING',
  34. LOG_NOTICE => 'NOTICE',
  35. LOG_INFO => 'INFO',
  36. LOG_DEBUG => 'DEBUG',
  37. ];
  38. /**
  39. * @var int Level to use for stack traces
  40. */
  41. public static $strace_level = LOG_DEBUG;
  42. /**
  43. * Write an array of messages.
  44. *
  45. * $writer->write($messages);
  46. *
  47. * @param array $messages
  48. * @return void
  49. */
  50. abstract public function write(array $messages);
  51. /**
  52. * Allows the writer to have a unique key when stored.
  53. *
  54. * echo $writer;
  55. *
  56. * @return string
  57. */
  58. final public function __toString()
  59. {
  60. return spl_object_hash($this);
  61. }
  62. /**
  63. * Formats a log entry.
  64. *
  65. * @param array $message
  66. * @param string $format
  67. * @return string
  68. */
  69. public function format_message(array $message, $format = "time --- level: body in file:line")
  70. {
  71. $message['time'] = Date::formatted_time('@'.$message['time'], Log_Writer::$timestamp, Log_Writer::$timezone, TRUE);
  72. $message['level'] = $this->_log_levels[$message['level']];
  73. $string = strtr($format, array_filter($message, 'is_scalar'));
  74. if (isset($message['additional']['exception']))
  75. {
  76. // Re-use as much as possible, just resetting the body to the trace
  77. $message['body'] = $message['additional']['exception']->getTraceAsString();
  78. $message['level'] = $this->_log_levels[Log_Writer::$strace_level];
  79. $string .= PHP_EOL.strtr($format, array_filter($message, 'is_scalar'));
  80. }
  81. return $string;
  82. }
  83. }