Switchlog.class.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /* *
  3. * Log A logger class which creates logs when an exception is thrown.
  4. * @author Author: Vivek Wicky Aswal. (https://twitter.com/#!/VivekWickyAswal)
  5. * @git https://github.com/indieteq/PHP-MySQL-PDO-Database-Class
  6. * @version 0.1a
  7. */
  8. class Switchlog {
  9. # @string, Log directory name
  10. private $path = 'runtime/';
  11. /**
  12. * 设置记录日志标志
  13. *
  14. * @param $bLogFlag : true - 记录; 其他 - 不记录
  15. */
  16. private $bLogFlag = false;
  17. # @void, Default Constructor, Sets the timezone and path of the log files.
  18. public function __construct($bLogFlag = false) {
  19. date_default_timezone_set('Asia/Shanghai');
  20. $this->path = SITE_PATH.'sdk/runtime/';
  21. $this->bLogFlag = $bLogFlag;
  22. }
  23. /**
  24. * @void
  25. * Creates the log
  26. *
  27. * @param string $message the message which is written into the log.
  28. *
  29. * @description:
  30. * 1. Checks if directory exists, if not, create one and call this method again.
  31. * 2. Checks if log already exists.
  32. * 3. If not, new log gets created. Log is written into the logs folder.
  33. * 4. Logname is current date(Year - Month - Day).
  34. * 5. If log exists, edit method called.
  35. * 6. Edit method modifies the current log.
  36. */
  37. public function write($message, $logname = '') {
  38. //false不记录
  39. if ($this->bLogFlag == false) {
  40. return;
  41. }
  42. $date = new DateTime();
  43. if (empty($logname)) {
  44. $logname = 'db';
  45. }
  46. $log = $this->path.$logname.'/'.$date->format('Y-m-d').".txt";
  47. if (is_dir($this->path.$logname.'/')) {
  48. if (!file_exists($log)) {
  49. $fh = fopen($log, 'a+') or die("Fatal Error !");
  50. $logcontent = "Time : ".$date->format('H:i:s')."\r\n".$message."\r\n";
  51. fwrite($fh, $logcontent);
  52. fclose($fh);
  53. } else {
  54. $this->edit($log, $date, $message);
  55. }
  56. } else {
  57. if (mkdir($this->path.$logname.'/', 0777) === true) {
  58. $this->write($message, $logname);
  59. }
  60. }
  61. }
  62. /**
  63. * @void
  64. * Gets called if log exists.
  65. * Modifies current log and adds the message to the log.
  66. *
  67. * @param string $log
  68. * @param DateTimeObject $date
  69. * @param string $message
  70. */
  71. private function edit($log, $date, $message) {
  72. $logcontent = "Time : ".$date->format('H:i:s')."\r\n".$message."\r\n\r\n";
  73. $logcontent = $logcontent.file_get_contents($log);
  74. file_put_contents($log, $logcontent);
  75. }
  76. }
  77. ?>