PageRenderTime 54ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/framework/F3/log.php

https://bitbucket.org/lxa478/qcrt
PHP | 97 lines | 47 code | 9 blank | 41 comment | 5 complexity | f066a8f0a7a38db0e704c0b390231aa4 MD5 | raw file
Possible License(s): GPL-3.0
  1. <?php
  2. /**
  3. Custom Log for the PHP Fat-Free Framework
  4. The contents of this file are subject to the terms of the GNU General
  5. Public License Version 3.0. You may not use this file except in
  6. compliance with the license. Any of the license terms and conditions
  7. can be waived if you get permission from the copyright holder.
  8. Copyright (c) 2009-2012 F3::Factory
  9. Bong Cosca <bong.cosca@yahoo.com>
  10. @package Log
  11. @version 2.1.0
  12. **/
  13. //! Custom log plugin
  14. class Log extends Base {
  15. //@{ Locale-specific error/exception messages
  16. const
  17. TEXT_LogOpen='Unable to open log file',
  18. TEXT_LogLock='Unable to gain exclusive access to log file';
  19. //@}
  20. const
  21. //! Seconds before framework gives up trying to lock resource
  22. LOG_Timeout=30,
  23. //! Maximum log file size
  24. LOG_Size='2M';
  25. //@{
  26. //! Log file properties
  27. private
  28. $filename,$handle;
  29. //@}
  30. /**
  31. Write specified text to log file
  32. @param $text string
  33. @public
  34. **/
  35. function write($text) {
  36. if (!flock($this->handle,LOCK_EX|LOCK_NB)) {
  37. // Lock attempt failed
  38. trigger_error(self::TEXT_LogLock);
  39. return;
  40. }
  41. clearstatcache();
  42. if (filesize($this->filename)>self::bytes(self::LOG_Size)) {
  43. // Perform log rotation sequence
  44. if (is_file($this->filename.'.1'))
  45. copy($this->filename.'.1',$this->filename.'.2');
  46. copy($this->filename,$this->filename.'.1');
  47. ftruncate($this->handle,0);
  48. }
  49. // Prepend text with timestamp, source IP, file name and
  50. // line number for tracking origin
  51. $trace=debug_backtrace(FALSE);
  52. fwrite(
  53. $this->handle,
  54. date('r').
  55. (isset($_SERVER['REMOTE_ADDR'])?
  56. (' ['.$_SERVER['REMOTE_ADDR'].'] '):'').
  57. self::fixslashes($trace[0]['file']).':'.
  58. $trace[0]['line'].' '.
  59. preg_replace('/\s+/',' ',$text)."\n"
  60. );
  61. flock($this->handle,LOCK_UN);
  62. }
  63. /**
  64. Logger constructor
  65. @param $file string
  66. @public
  67. **/
  68. function __construct($file) {
  69. $this->filename=$this->ref('LOGS').$file;
  70. $this->handle=fopen($this->filename,'a+');
  71. if (!is_resource($this->handle)) {
  72. // Unable to open file
  73. trigger_error(self::TEXT_LogOpen);
  74. return;
  75. }
  76. }
  77. /**
  78. Logger destructor
  79. @public
  80. **/
  81. function __destruct() {
  82. if (is_resource($this->handle))
  83. fclose($this->handle);
  84. }
  85. }