File.class.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | TOPThink [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2011 http://topthink.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. namespace Think\Log\Driver;
  12. class File {
  13. protected $config = array(
  14. 'log_time_format' => ' c ',
  15. 'log_file_size' => 2097152,
  16. 'log_path' => '',
  17. );
  18. // 实例化并传入参数
  19. public function __construct($config=array()){
  20. $this->config = array_merge($this->config,$config);
  21. }
  22. /**
  23. * 日志写入接口
  24. * @access public
  25. * @param string $log 日志信息
  26. * @param string $destination 写入目标
  27. * @return void
  28. */
  29. public function write($log,$destination='') {
  30. $now = date($this->config['log_time_format']);
  31. if(empty($destination))
  32. $destination = $this->config['log_path'].date('y_m_d').'.log';
  33. // 自动创建日志目录
  34. $log_dir = dirname($destination);
  35. if (!is_dir($log_dir)) {
  36. mkdir($log_dir, 0755, true);
  37. }
  38. //检测日志文件大小,超过配置大小则备份日志文件重新生成
  39. if(is_file($destination) && floor($this->config['log_file_size']) <= filesize($destination) )
  40. rename($destination,dirname($destination).'/'.time().'-'.basename($destination));
  41. error_log("[{$now}] ".$_SERVER['REMOTE_ADDR'].' '.$_SERVER['REQUEST_URI']."\r\n{$log}\r\n", 3,$destination);
  42. }
  43. }