File.php 2.2 KB

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