icingaweb2/library/Icinga/Application/Logger/Writer/FileWriter.php

82 lines
2.1 KiB
PHP
Raw Normal View History

2014-02-26 13:47:16 +01:00
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Application\Logger\Writer;
2014-02-26 13:47:16 +01:00
use Exception;
use Icinga\Data\ConfigObject;
use Icinga\Application\Logger;
use Icinga\Application\Logger\LogWriter;
use Icinga\Exception\ConfigurationError;
use Icinga\Util\File;
2014-02-26 13:47:16 +01:00
/**
* Log to a file
2014-02-26 13:47:16 +01:00
*/
class FileWriter extends LogWriter
2014-02-26 13:47:16 +01:00
{
/**
* Path to the file
2014-02-26 13:47:16 +01:00
*
* @var string
*/
protected $file;
2014-02-26 13:47:16 +01:00
/**
* Create a new file log writer
*
* @param ConfigObject $config
*
* @throws ConfigurationError If the configuration directive 'file' is missing or if the path to 'file' does
* not exist or if writing to 'file' is not possible
2014-02-26 13:47:16 +01:00
*/
public function __construct(ConfigObject $config)
2014-02-26 13:47:16 +01:00
{
if ($config->file === null) {
throw new ConfigurationError('Required logging configuration directive \'file\' missing');
}
$this->file = $config->file;
if (substr($this->file, 0, 6) !== 'php://' && ! file_exists(dirname($this->file))) {
throw new ConfigurationError(
'Log path "%s" does not exist',
dirname($this->file)
);
}
try {
$this->write(''); // Avoid to handle such errors on every write access
} catch (Exception $e) {
throw new ConfigurationError(
'Cannot write to log file "%s" (%s)',
$this->file,
$e->getMessage()
);
}
2014-02-26 13:47:16 +01:00
}
/**
* Log a message
2014-02-26 13:47:16 +01:00
*
* @param int $level The logging level
* @param string $message The log message
2014-02-26 13:47:16 +01:00
*/
public function log($level, $message)
2014-02-26 13:47:16 +01:00
{
$this->write(date('c') . ' - ' . Logger::$levels[$level] . ' - ' . $message . PHP_EOL);
2014-02-26 13:47:16 +01:00
}
/**
* Write a message to the log
2014-02-26 13:47:16 +01:00
*
* @param string $message
2014-02-26 13:47:16 +01:00
*/
protected function write($message)
2014-02-26 13:47:16 +01:00
{
$file = new File($this->file, 'a');
$file->fwrite($message);
$file->fflush();
2014-02-26 13:47:16 +01:00
}
}