File.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * File log writer. Writes out messages and stores them in a YYYY/MM directory.
  4. *
  5. * @package KO7
  6. * @category Logging
  7. *
  8. * @copyright (c) 2007-2016 Kohana Team
  9. * @copyright (c) since 2016 Koseven Team
  10. * @license https://koseven.dev/LICENSE
  11. */
  12. class KO7_Log_File extends Log_Writer {
  13. /**
  14. * @var string Directory to place log files in
  15. */
  16. protected $_directory;
  17. /**
  18. * Creates a new file logger. Checks that the directory exists and
  19. * is writable.
  20. *
  21. * $writer = new Log_File($directory);
  22. *
  23. * @param string $directory log directory
  24. * @return void
  25. */
  26. public function __construct($directory)
  27. {
  28. if ( ! is_dir($directory) OR ! is_writable($directory))
  29. {
  30. throw new KO7_Exception('Directory :dir must be writable',
  31. [':dir' => Debug::path($directory)]);
  32. }
  33. // Determine the directory path
  34. $this->_directory = realpath($directory).DIRECTORY_SEPARATOR;
  35. }
  36. /**
  37. * Writes each of the messages into the log file. The log file will be
  38. * appended to the `YYYY/MM/DD.log.php` file, where YYYY is the current
  39. * year, MM is the current month, and DD is the current day.
  40. *
  41. * $writer->write($messages);
  42. *
  43. * @param array $messages
  44. * @return void
  45. */
  46. public function write(array $messages)
  47. {
  48. // Set the yearly directory name
  49. $directory = $this->_directory.date('Y');
  50. if ( ! is_dir($directory))
  51. {
  52. // Create the yearly directory
  53. mkdir($directory, 02777);
  54. // Set permissions (must be manually set to fix umask issues)
  55. chmod($directory, 02777);
  56. }
  57. // Add the month to the directory
  58. $directory .= DIRECTORY_SEPARATOR.date('m');
  59. if ( ! is_dir($directory))
  60. {
  61. // Create the monthly directory
  62. mkdir($directory, 02777);
  63. // Set permissions (must be manually set to fix umask issues)
  64. chmod($directory, 02777);
  65. }
  66. // Set the name of the log file
  67. $filename = $directory.DIRECTORY_SEPARATOR.date('d').EXT;
  68. if ( ! file_exists($filename))
  69. {
  70. // Create the log file
  71. file_put_contents($filename, NULL);
  72. // Allow anyone to write to log files
  73. chmod($filename, 0666);
  74. }
  75. foreach ($messages as $message)
  76. {
  77. // Write each message into the log file
  78. file_put_contents($filename, PHP_EOL.$this->format_message($message), FILE_APPEND);
  79. }
  80. }
  81. }