Skip to content

Commit

Permalink
feature 3221 Lazy log file open, clean code
Browse files Browse the repository at this point in the history
git-svn-id: http://piwigo.org/svn/trunk@31103 68402e56-0260-453c-a942-63ccdbb3a9ee
  • Loading branch information
mistic100 committed Apr 24, 2015
1 parent 0c576ea commit 271e1f5
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 47 deletions.
8 changes: 5 additions & 3 deletions admin/include/image.class.php
Expand Up @@ -621,6 +621,8 @@ function compose($overlay, $x, $y, $opacity)

function write($destination_filepath)
{
global $logger;

$this->add_command('interlace', 'line'); // progressive rendering
// use 4:2:2 chroma subsampling (reduce file size by 20-30% with "almost" no human perception)
//
Expand Down Expand Up @@ -648,13 +650,13 @@ function write($destination_filepath)

$dest = pathinfo($destination_filepath);
$exec .= ' "'.realpath($dest['dirname']).'/'.$dest['basename'].'" 2>&1';
$logger->debug($exec, 'i.php');
@exec($exec, $returnarray);

if (function_exists('ilog')) ilog($exec);
if (is_array($returnarray) && (count($returnarray)>0) )
{
if (function_exists('ilog')) ilog('ERROR', $returnarray);
foreach($returnarray as $line)
$logger->error('', 'i.php', $returnarray);
foreach ($returnarray as $line)
trigger_error($line, E_USER_WARNING);
}
return is_array($returnarray);
Expand Down
4 changes: 2 additions & 2 deletions i.php
Expand Up @@ -614,9 +614,9 @@ function send_derivative($expires)

$timing['total'] = time_step($begin);

if ($logger->severity() >= Logger::INFO)
if ($logger->severity() >= Logger::DEBUG)
{
$logger->info('perf', 'i.php', array(
$logger->debug('', 'i.php', array(
'src_path' => basename($page['src_path']),
'derivative_path' => basename($page['derivative_path']),
'o_size' => $o_size[0] . ' ' . $o_size[1] . ' ' . ($o_size[0]*$o_size[1]),
Expand Down
119 changes: 77 additions & 42 deletions include/Logger.class.php
Expand Up @@ -95,6 +95,7 @@ class Logger
*/
private $_fileHandle = null;


/**
* Class constructor.
*
Expand All @@ -105,42 +106,59 @@ public function __construct($options)
{
$this->options = array_merge($this->options, $options);

if (is_string($this->options['severity'])) {
if (is_string($this->options['severity']))
{
$this->options['severity'] = self::codeToLevel($this->options['severity']);
}

if ($this->options['severity'] === self::OFF) {
if ($this->options['severity'] === self::OFF)
{
return;
}

$this->options['directory'] = rtrim($this->options['directory'], '\\/') . DIRECTORY_SEPARATOR;

if ($this->options['filename'] == null) {
if ($this->options['filename'] == null)
{
$this->options['filename'] = 'log_' . date('Y-m-d') . '.txt';
}

$this->options['filePath'] = $this->options['directory'] . $this->options['filename'];

if (!file_exists($this->options['directory'])) {
mkgetdir($this->options['directory'], MKGETDIR_DEFAULT|MKGETDIR_PROTECT_HTACCESS);
}

if (file_exists($this->options['filePath']) && !is_writable($this->options['filePath'])) {
$this->_logStatus = self::STATUS_OPEN_FAILED;
throw new RuntimeException(self::$_messages['writefail']);
return;
if ($this->options['archiveDays'] != self::ARCHIVE_NO_PURGE && rand() % 97 == 0)
{
$this->purge();
}
}

/**
* Open the log file if not already oppenned
*/
private function open()
{
if ($this->status() == self::STATUS_LOG_CLOSED)
{
if (!file_exists($this->options['directory']))
{
mkgetdir($this->options['directory'], MKGETDIR_DEFAULT|MKGETDIR_PROTECT_HTACCESS);
}

if (($this->_fileHandle = fopen($this->options['filePath'], 'a'))) {
$this->_logStatus = self::STATUS_LOG_OPEN;
}
else {
$this->_logStatus = self::STATUS_OPEN_FAILED;
throw new RuntimeException(self::$_messages['openfail']);
}
if (file_exists($this->options['filePath']) && !is_writable($this->options['filePath']))
{
$this->_logStatus = self::STATUS_OPEN_FAILED;
throw new RuntimeException(self::$_messages['writefail']);
return;
}

if ($this->options['archiveDays'] != self::ARCHIVE_NO_PURGE && rand() % 97 == 0) {
$this->purge();
if (($this->_fileHandle = fopen($this->options['filePath'], 'a')) != false)
{
$this->_logStatus = self::STATUS_LOG_OPEN;
}
else
{
$this->_logStatus = self::STATUS_OPEN_FAILED;
throw new RuntimeException(self::$_messages['openfail']);
}
}
}

Expand All @@ -149,7 +167,8 @@ public function __construct($options)
*/
public function __destruct()
{
if ($this->_fileHandle) {
if ($this->_fileHandle)
{
fclose($this->_fileHandle);
}
}
Expand Down Expand Up @@ -280,8 +299,10 @@ public function emergency($line, $cat = null, $args = array())
*/
public function log($severity, $message, $cat = null, $args = array())
{
if ($this->severity() >= $severity) {
if (is_array($cat)) {
if ($this->severity() >= $severity)
{
if (is_array($cat))
{
$args = $cat;
$cat = null;
}
Expand All @@ -297,8 +318,11 @@ public function log($severity, $message, $cat = null, $args = array())
*/
public function write($line)
{
if ($this->_logStatus == self::STATUS_LOG_OPEN) {
if (fwrite($this->_fileHandle, $line) === false) {
$this->open();
if ($this->status() == self::STATUS_LOG_OPEN)
{
if (fwrite($this->_fileHandle, $line) === false)
{
throw new RuntimeException(self::$_messages['writefail']);
}
}
Expand All @@ -307,12 +331,15 @@ public function write($line)
/**
* Purges files matching 'globPattern' older than 'archiveDays'.
*/
public function purge() {
public function purge()
{
$files = glob($this->options['directory'] . $this->options['globPattern']);
$limit = time() - $this->options['archiveDays'] * 86400;

foreach ($files as $file) {
if (@filemtime($file) < $limit) {
foreach ($files as $file)
{
if (@filemtime($file) < $limit)
{
@unlink($file);
}
}
Expand All @@ -328,12 +355,14 @@ public function purge() {
*/
private function formatMessage($level, $message, $cat, $context)
{
if (!empty($context)) {
$message .= "\n" . $this->indent($this->contextToString($context));
if (!empty($context))
{
$message.= "\n" . $this->indent($this->contextToString($context));
}
$line = "[" . $this->getTimestamp() . "]\t[" . self::levelToCode($level) . "]\t";
if ($cat != null) {
$line .= "[" . $cat . "]\t";
if ($cat != null)
{
$line.= "[" . $cat . "]\t";
}
return $line . $message . "\n";
}
Expand All @@ -349,7 +378,7 @@ private function formatMessage($level, $message, $cat, $context)
private function getTimestamp()
{
$originalTime = microtime(true);
$micro = sprintf("%06d", ($originalTime - floor($originalTime)) * 1000000);
$micro = sprintf('%06d', ($originalTime - floor($originalTime)) * 1000000);
$date = new DateTime(date('Y-m-d H:i:s.'.$micro, $originalTime));
return $date->format($this->options['dateFormat']);
}
Expand All @@ -363,18 +392,22 @@ private function getTimestamp()
private function contextToString($context)
{
$export = '';
foreach ($context as $key => $value) {
$export .= "{$key}: ";
$export .= preg_replace(array(
foreach ($context as $key => $value)
{
$export.= $key . ': ';
$export.= preg_replace(array(
'/=>\s+([a-zA-Z])/im',
'/array\(\s+\)/im',
'/^ |\G /m'
), array(
),
array(
'=> $1',
'array()',
' '
), str_replace('array (', 'array(', var_export($value, true)));
$export .= PHP_EOL;
),
str_replace('array (', 'array(', var_export($value, true))
);
$export.= PHP_EOL;
}
return str_replace(array('\\\\', '\\\''), array('\\', '\''), rtrim($export));
}
Expand All @@ -388,7 +421,7 @@ private function contextToString($context)
*/
private function indent($string, $indent = ' ')
{
return $indent.str_replace("\n", "\n".$indent, $string);
return $indent . str_replace("\n", "\n" . $indent, $string);
}

/**
Expand All @@ -399,7 +432,8 @@ private function indent($string, $indent = ' ')
*/
static function levelToCode($level)
{
switch ($level) {
switch ($level)
{
case self::EMERGENCY:
return 'EMERGENCY';
case self::ALERT:
Expand Down Expand Up @@ -429,7 +463,8 @@ static function levelToCode($level)
*/
static function codeToLevel($code)
{
switch (strtoupper($code)) {
switch (strtoupper($code))
{
case 'EMERGENCY':
return self::EMERGENCY;
case 'ALERT':
Expand Down

0 comments on commit 271e1f5

Please sign in to comment.