diff --git a/README.md b/README.md index 8aadca1..08f5da1 100644 --- a/README.md +++ b/README.md @@ -58,3 +58,10 @@ return [ (Since 1.2.0) * (*string|null*) `$replaceNewline` a string that should replace all newline characters in a log message. Default ist `null` for no replacement. (Since 1.1.0) + * (*bool*) `$disableTimestamp` whether to omit the timestamp prefix. The default is `false` which + will prepend every message with a timestamp generated by `yii\log\Target::getTime()`. + * (*string*) `$prefixString` a string that will be prefixed to every message at the first position + (even before the timestamp - if not disabled). Default is an empty string. + * (*bool*) `$enableLocking` whether enable locking with `flock()` on the target. Note, that this is not + supported by all stream types. Default is `false`. + diff --git a/src/Target.php b/src/Target.php index 9d56a54..84a71ae 100644 --- a/src/Target.php +++ b/src/Target.php @@ -1,6 +1,7 @@ openedFp) { - fclose($this->fp); + @fclose($this->fp); } } @@ -66,9 +87,9 @@ public function setFp($value) */ public function getFp() { - if ($this->fp===null) { + if ($this->fp === null) { $this->fp = @fopen($this->url,'w'); - if ($this->fp===false) { + if ($this->fp === false) { throw new InvalidConfigException("Unable to open '{$this->url}' for writing."); } $this->openedFp = true; @@ -79,11 +100,22 @@ public function getFp() /** * Writes a log message to the given target URL * @throws InvalidConfigException if unable to open the stream for writing + * @throws LogRuntimeException if unable to write log */ public function export() { $text = implode("\n", array_map([$this, 'formatMessage'], $this->messages)) . "\n"; - fwrite($this->getFp(), $text); + $fp = $this->getFp(); + if ($this->enableLocking) { + @flock($fp, LOCK_EX); + } + if (@fwrite($fp, $text) === false) { + $error = error_get_last(); + throw new LogRuntimeException("Unable to export log!: {$error['message']}"); + } + if ($this->enableLocking) { + @flock($fp, LOCK_UN); + } } /** @@ -91,11 +123,17 @@ public function export() */ public function formatMessage($message) { - $text = parent::formatMessage($message); - if ($this->replaceNewline===null) { - return $text; - } else { - return str_replace("\n", $this->replaceNewline, $text); - } + $text = $this->prefixString . trim(parent::formatMessage($message)); + return $this->replaceNewline === null ? + $text : + str_replace("\n", $this->replaceNewline, $text); + } + + /** + * @inheritdoc + */ + protected function getTime($timestamp) + { + return $this->disableTimestamp ? '' : parent::getTime($timestamp); } }