1<?php 2 3namespace dokuwiki; 4 5class Logger 6{ 7 const LOG_ERROR = 'error'; 8 const LOG_DEPRECATED = 'deprecated'; 9 const LOG_DEBUG = 'debug'; 10 11 /** @var Logger[] */ 12 static protected $instances; 13 14 /** @var string what kind of log is this */ 15 protected $facility; 16 17 /** 18 * Logger constructor. 19 * 20 * @param string $facility The type of log 21 */ 22 protected function __construct($facility) 23 { 24 $this->facility = $facility; 25 } 26 27 /** 28 * Return a Logger instance for the given facility 29 * 30 * @param string $facility The type of log 31 * @return Logger 32 */ 33 static public function getInstance($facility = self::LOG_ERROR) 34 { 35 if (self::$instances[$facility] === null) { 36 self::$instances[$facility] = new Logger($facility); 37 } 38 return self::$instances[$facility]; 39 } 40 41 /** 42 * Log a message to the facility log 43 * 44 * @param string $message The log message 45 * @param mixed $details Any details that should be added to the log entry 46 * @param string $file A source filename if this is related to a source position 47 * @param int $line A line number for the above file 48 * @return bool 49 */ 50 public function log($message, $details = null, $file = '', $line = 0) 51 { 52 // details are logged indented 53 if ($details) { 54 if (!is_string($details)) { 55 $details = json_encode($details, JSON_PRETTY_PRINT); 56 } 57 $details = explode("\n", $details); 58 $loglines = array_map(function ($line) { 59 return ' ' . $line; 60 }, $details); 61 } elseif ($details) { 62 $loglines = [$details]; 63 } else { 64 $loglines = []; 65 } 66 67 // datetime, fileline, message 68 $logline = gmdate('Y-m-d H:i:s') . "\t"; 69 if ($file) { 70 $logline .= $file; 71 if ($line) $logline .= "($line)"; 72 } 73 $logline .= "\t" . $message; 74 75 array_unshift($loglines, $logline); 76 return $this->writeLogLines($loglines); 77 } 78 79 /** 80 * Construct the log file for the given day 81 * 82 * @param false|string|int $date Date to access, false for today 83 * @return string 84 */ 85 public function getLogfile($date = false) 86 { 87 global $conf; 88 89 if ($date !== null) $date = strtotime($date); 90 if (!$date) $date = time(); 91 92 return $conf['logdir'] . '/' . $this->facility . '/' . date('Y-m-d', $date) . '.log'; 93 } 94 95 /** 96 * Write the given lines to today's facility log 97 * 98 * @param string[] $lines the raw lines to append to the log 99 * @return bool true if the log was written 100 */ 101 protected function writeLogLines($lines) 102 { 103 $logfile = $this->getLogfile(); 104 return io_saveFile($logfile, join("\n", $lines) . "\n", true); 105 } 106} 107