Skip to content

Commit

Permalink
Call mkdir and file_put_contents once to improve performance
Browse files Browse the repository at this point in the history
- Returns early if there's nothing to write
- Call `mkdir` once with recursive flag on
- Prepare string to write and call `file_put_contents` once
  • Loading branch information
enov committed Dec 16, 2015
1 parent d14ef3a commit 1242079
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 18 deletions.
28 changes: 12 additions & 16 deletions classes/Kohana/Log/File.php
Expand Up @@ -48,25 +48,21 @@ public function __construct($directory)
*/
public function write(array $messages)
{
// Set the yearly directory name
$directory = $this->_directory.date('Y');

if ( ! is_dir($directory))
if (
empty($messages)
OR
empty($filtered_messages = $this->filter($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 +80,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);
}

}
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 1242079

Please sign in to comment.