Skip to content

Commit

Permalink
Merge pull request #649 from kohana/3.4/feature/log-writer-file-perfo…
Browse files Browse the repository at this point in the history
…rmance

Call `mkdir` and `file_put_contents` once to improve performance
  • Loading branch information
acoulton committed Dec 16, 2015
2 parents d14ef3a + b3bbbd1 commit 67c6ca7
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 17 deletions.
25 changes: 10 additions & 15 deletions classes/Kohana/Log/File.php
Expand Up @@ -48,25 +48,20 @@ public function __construct($directory)
*/
public function write(array $messages)
{
// Set the yearly directory name
$directory = $this->_directory.date('Y');
$filtered_messages = $this->filter($messages);

if ( ! is_dir($directory))
if (empty($filtered_messages))
{
// Create the yearly directory
mkdir($directory, 02777);

// Set permissions (must be manually set to fix umask issues)
chmod($directory, 02777);
return;
}

// Add the month to the directory
$directory .= DIRECTORY_SEPARATOR.date('m');
// Set the yearly and monthly directory name
$directory = $this->_directory . date('Y' . DIRECTORY_SEPARATOR . 'm');

if ( ! is_dir($directory))
{
// Create the monthly directory
mkdir($directory, 02777);
mkdir($directory, 02777, TRUE);

// Set permissions (must be manually set to fix umask issues)
chmod($directory, 02777);
Expand All @@ -84,13 +79,13 @@ public function write(array $messages)
chmod($filename, 0666);
}

$filtered_messages = $this->filter($messages);

$formatted_messages = array();
foreach ($filtered_messages as $message)
{
// Write each message into the log file
file_put_contents($filename, $this->format_message($message).PHP_EOL, FILE_APPEND);
$formatted_messages[] = $this->format_message($message);
}

file_put_contents($filename, implode(PHP_EOL, $formatted_messages).PHP_EOL, FILE_APPEND);
}

}
5 changes: 5 additions & 0 deletions classes/Kohana/Log/Writer.php
Expand Up @@ -197,6 +197,11 @@ public function detach_filter(Kohana_Log_Filter $filter)
*/
public function filter(array $messages)
{
if (empty($messages))
{
return [];
}

foreach ($this->filters as $filter)
{
$messages = $filter->process($messages);
Expand Down
11 changes: 9 additions & 2 deletions tests/kohana/Log/FileTest.php
Expand Up @@ -178,7 +178,7 @@ protected function make_dummy_written_logs(array $levels)
$file_header = '<?php exit; ?>' . PHP_EOL . PHP_EOL;

if (empty($levels)) {
return $file_header;
return NULL;
}

$logs = array();
Expand Down Expand Up @@ -219,7 +219,14 @@ public function get_filename()

public function get_written_logs()
{
return file_get_contents($this->get_directory() . $this->get_filename());
$file = $this->get_directory() . $this->get_filename();

if ( ! is_file($file))
{
return NULL;
}

return file_get_contents($file);
}

}

0 comments on commit 67c6ca7

Please sign in to comment.