Log.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP
  6. *
  7. * This content is released under the MIT License (MIT)
  8. *
  9. * Copyright (c) 2014 - 2019, British Columbia Institute of Technology
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. * THE SOFTWARE.
  28. *
  29. * @package CodeIgniter
  30. * @author EllisLab Dev Team
  31. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
  32. * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/)
  33. * @license https://opensource.org/licenses/MIT MIT License
  34. * @link https://codeigniter.com
  35. * @since Version 1.0.0
  36. * @filesource
  37. */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39. /**
  40. * Logging Class
  41. *
  42. * @package CodeIgniter
  43. * @subpackage Libraries
  44. * @category Logging
  45. * @author EllisLab Dev Team
  46. * @link https://codeigniter.com/user_guide/general/errors.html
  47. */
  48. class CI_Log {
  49. /**
  50. * Path to save log files
  51. *
  52. * @var string
  53. */
  54. protected $_log_path;
  55. /**
  56. * File permissions
  57. *
  58. * @var int
  59. */
  60. protected $_file_permissions = 0644;
  61. /**
  62. * Level of logging
  63. *
  64. * @var int
  65. */
  66. protected $_threshold = 1;
  67. /**
  68. * Array of threshold levels to log
  69. *
  70. * @var array
  71. */
  72. protected $_threshold_array = array();
  73. /**
  74. * Format of timestamp for log files
  75. *
  76. * @var string
  77. */
  78. protected $_date_fmt = 'Y-m-d H:i:s';
  79. /**
  80. * Filename extension
  81. *
  82. * @var string
  83. */
  84. protected $_file_ext;
  85. /**
  86. * Whether or not the logger can write to the log files
  87. *
  88. * @var bool
  89. */
  90. protected $_enabled = TRUE;
  91. /**
  92. * Predefined logging levels
  93. *
  94. * @var array
  95. */
  96. protected $_levels = array('ERROR' => 1, 'DEBUG' => 2, 'INFO' => 3, 'ALL' => 4);
  97. /**
  98. * mbstring.func_overload flag
  99. *
  100. * @var bool
  101. */
  102. protected static $func_overload;
  103. // --------------------------------------------------------------------
  104. /**
  105. * Class constructor
  106. *
  107. * @return void
  108. */
  109. public function __construct()
  110. {
  111. $config =& get_config();
  112. isset(self::$func_overload) OR self::$func_overload = (extension_loaded('mbstring') && ini_get('mbstring.func_overload'));
  113. $this->_log_path = ($config['log_path'] !== '') ? $config['log_path'] : APPPATH.'logs/';
  114. $this->_file_ext = (isset($config['log_file_extension']) && $config['log_file_extension'] !== '')
  115. ? ltrim($config['log_file_extension'], '.') : 'php';
  116. file_exists($this->_log_path) OR mkdir($this->_log_path, 0755, TRUE);
  117. if ( ! is_dir($this->_log_path) OR ! is_really_writable($this->_log_path))
  118. {
  119. $this->_enabled = FALSE;
  120. }
  121. if (is_numeric($config['log_threshold']))
  122. {
  123. $this->_threshold = (int) $config['log_threshold'];
  124. }
  125. elseif (is_array($config['log_threshold']))
  126. {
  127. $this->_threshold = 0;
  128. $this->_threshold_array = array_flip($config['log_threshold']);
  129. }
  130. if ( ! empty($config['log_date_format']))
  131. {
  132. $this->_date_fmt = $config['log_date_format'];
  133. }
  134. if ( ! empty($config['log_file_permissions']) && is_int($config['log_file_permissions']))
  135. {
  136. $this->_file_permissions = $config['log_file_permissions'];
  137. }
  138. }
  139. // --------------------------------------------------------------------
  140. /**
  141. * Write Log File
  142. *
  143. * Generally this function will be called using the global log_message() function
  144. *
  145. * @param string $level The error level: 'error', 'debug' or 'info'
  146. * @param string $msg The error message
  147. * @return bool
  148. */
  149. public function write_log($level, $msg)
  150. {
  151. if ($this->_enabled === FALSE)
  152. {
  153. return FALSE;
  154. }
  155. $level = strtoupper($level);
  156. if (( ! isset($this->_levels[$level]) OR ($this->_levels[$level] > $this->_threshold))
  157. && ! isset($this->_threshold_array[$this->_levels[$level]]))
  158. {
  159. return FALSE;
  160. }
  161. $filepath = $this->_log_path.'log-'.date('Y-m-d').'.'.$this->_file_ext;
  162. $message = '';
  163. if ( ! file_exists($filepath))
  164. {
  165. $newfile = TRUE;
  166. // Only add protection to php files
  167. if ($this->_file_ext === 'php')
  168. {
  169. $message .= "<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>\n\n";
  170. }
  171. }
  172. if ( ! $fp = @fopen($filepath, 'ab'))
  173. {
  174. return FALSE;
  175. }
  176. flock($fp, LOCK_EX);
  177. // Instantiating DateTime with microseconds appended to initial date is needed for proper support of this format
  178. if (strpos($this->_date_fmt, 'u') !== FALSE)
  179. {
  180. $microtime_full = microtime(TRUE);
  181. $microtime_short = sprintf("%06d", ($microtime_full - floor($microtime_full)) * 1000000);
  182. $date = new DateTime(date('Y-m-d H:i:s.'.$microtime_short, $microtime_full));
  183. $date = $date->format($this->_date_fmt);
  184. }
  185. else
  186. {
  187. $date = date($this->_date_fmt);
  188. }
  189. $message .= $this->_format_line($level, $date, $msg);
  190. for ($written = 0, $length = self::strlen($message); $written < $length; $written += $result)
  191. {
  192. if (($result = fwrite($fp, self::substr($message, $written))) === FALSE)
  193. {
  194. break;
  195. }
  196. }
  197. flock($fp, LOCK_UN);
  198. fclose($fp);
  199. if (isset($newfile) && $newfile === TRUE)
  200. {
  201. chmod($filepath, $this->_file_permissions);
  202. }
  203. return is_int($result);
  204. }
  205. // --------------------------------------------------------------------
  206. /**
  207. * Format the log line.
  208. *
  209. * This is for extensibility of log formatting
  210. * If you want to change the log format, extend the CI_Log class and override this method
  211. *
  212. * @param string $level The error level
  213. * @param string $date Formatted date string
  214. * @param string $message The log message
  215. * @return string Formatted log line with a new line character at the end
  216. */
  217. protected function _format_line($level, $date, $message)
  218. {
  219. return $level.' - '.$date.' --> '.$message.PHP_EOL;
  220. }
  221. // --------------------------------------------------------------------
  222. /**
  223. * Byte-safe strlen()
  224. *
  225. * @param string $str
  226. * @return int
  227. */
  228. protected static function strlen($str)
  229. {
  230. return (self::$func_overload)
  231. ? mb_strlen($str, '8bit')
  232. : strlen($str);
  233. }
  234. // --------------------------------------------------------------------
  235. /**
  236. * Byte-safe substr()
  237. *
  238. * @param string $str
  239. * @param int $start
  240. * @param int $length
  241. * @return string
  242. */
  243. protected static function substr($str, $start, $length = NULL)
  244. {
  245. if (self::$func_overload)
  246. {
  247. // mb_substr($str, $start, null, '8bit') returns an empty
  248. // string on PHP 5.3
  249. isset($length) OR $length = ($start >= 0 ? self::strlen($str) - $start : -$start);
  250. return mb_substr($str, $start, $length, '8bit');
  251. }
  252. return isset($length)
  253. ? substr($str, $start, $length)
  254. : substr($str, $start);
  255. }
  256. }