log.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. <?php
  2. //以下为日志
  3. interface ILogHandler
  4. {
  5. public function write($msg);
  6. }
  7. class CLogFileHandler implements ILogHandler
  8. {
  9. private $handle = null;
  10. public function __construct($file = '')
  11. {
  12. $this->handle = fopen($file,'a');
  13. }
  14. public function write($msg)
  15. {
  16. fwrite($this->handle, $msg, 4096);
  17. }
  18. public function __destruct()
  19. {
  20. fclose($this->handle);
  21. }
  22. }
  23. class Log
  24. {
  25. private $handler = null;
  26. private $level = 15;
  27. private static $instance = null;
  28. private function __construct(){}
  29. private function __clone(){}
  30. public static function Init($handler = null,$level = 15)
  31. {
  32. if(!self::$instance instanceof self)
  33. {
  34. self::$instance = new self();
  35. self::$instance->__setHandle($handler);
  36. self::$instance->__setLevel($level);
  37. }
  38. return self::$instance;
  39. }
  40. private function __setHandle($handler){
  41. $this->handler = $handler;
  42. }
  43. private function __setLevel($level)
  44. {
  45. $this->level = $level;
  46. }
  47. public static function DEBUG($msg)
  48. {
  49. self::$instance->write(1, $msg);
  50. }
  51. public static function WARN($msg)
  52. {
  53. self::$instance->write(4, $msg);
  54. }
  55. public static function ERROR($msg)
  56. {
  57. $debugInfo = debug_backtrace();
  58. $stack = "[";
  59. foreach($debugInfo as $key => $val){
  60. if(array_key_exists("file", $val)){
  61. $stack .= ",file:" . $val["file"];
  62. }
  63. if(array_key_exists("line", $val)){
  64. $stack .= ",line:" . $val["line"];
  65. }
  66. if(array_key_exists("function", $val)){
  67. $stack .= ",function:" . $val["function"];
  68. }
  69. }
  70. $stack .= "]";
  71. self::$instance->write(8, $stack . $msg);
  72. }
  73. public static function INFO($msg)
  74. {
  75. self::$instance->write(2, $msg);
  76. }
  77. private function getLevelStr($level)
  78. {
  79. switch ($level)
  80. {
  81. case 1:
  82. return 'debug';
  83. break;
  84. case 2:
  85. return 'info';
  86. break;
  87. case 4:
  88. return 'warn';
  89. break;
  90. case 8:
  91. return 'error';
  92. break;
  93. default:
  94. }
  95. }
  96. protected function write($level,$msg)
  97. {
  98. if(($level & $this->level) == $level )
  99. {
  100. $msg = '['.date('Y-m-d H:i:s').']['.$this->getLevelStr($level).'] '.$msg."\n";
  101. $this->handler->write($msg);
  102. }
  103. }
  104. }