PageRenderTime 38ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/ManaPHP/Log/Adapter/File.php

https://gitlab.com/szlongshu/manaphp
PHP | 79 lines | 41 code | 18 blank | 20 comment | 6 complexity | 3abf017a154d4048367d20c160dce505 MD5 | raw file
  1. <?php
  2. namespace ManaPHP\Log\Adapter {
  3. use ManaPHP\Log\AdapterInterface;
  4. class File implements AdapterInterface
  5. {
  6. /**
  7. * @var string
  8. */
  9. protected $_file;
  10. /**
  11. * @var array
  12. */
  13. protected $_options = [];
  14. /**
  15. * @var bool
  16. */
  17. protected $_firstLog = true;
  18. /**
  19. * \ManaPHP\Log\Adapter\File constructor.
  20. *
  21. * @param string $file
  22. * @param array $options
  23. */
  24. public function __construct($file, $options = [])
  25. {
  26. $this->_file = $file;
  27. if (!isset($options['dateFormat'])) {
  28. $options['dateFormat'] = 'D, d M y H:i:s O';
  29. }
  30. if (!isset($options['format'])) {
  31. $options['format'] = '[%date%][%level%] %message%';
  32. }
  33. $this->_options = $options;
  34. }
  35. /**
  36. * @param string $level
  37. * @param string $message
  38. * @param array $context
  39. */
  40. public function log($level, $message, $context = [])
  41. {
  42. if ($this->_firstLog) {
  43. $dir = dirname($this->_file);
  44. if (!@mkdir($dir, 0755, true) && !is_dir($dir)) {
  45. error_log('Unable to create \'' . $dir . '\' directory: ' . error_get_last()['message']);
  46. }
  47. $this->_firstLog = false;
  48. }
  49. $context['date'] = date($this->_options['dateFormat'], $context['date'] ?: time());
  50. $replaced = [];
  51. foreach ($context as $k => $v) {
  52. $replaced["%$k%"] = $v;
  53. }
  54. $replaced['%message%'] = $message . PHP_EOL;
  55. $log = strtr($this->_options['format'], $replaced);
  56. if (file_put_contents($this->_file, $log, FILE_APPEND | LOCK_EX) === false) {
  57. error_log('Write log to file failed: ' . $this->_file);
  58. }
  59. }
  60. }
  61. }