Writer.php 2.2 KB

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