-
-
Notifications
You must be signed in to change notification settings - Fork 53
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #222 from clue-labs/logstream
Refactor logging into new `LogStreamHandler`
- Loading branch information
Showing
8 changed files
with
352 additions
and
91 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
<?php | ||
|
||
namespace FrameworkX\Io; | ||
|
||
/** | ||
* @internal | ||
*/ | ||
class LogStreamHandler | ||
{ | ||
/** @var resource */ | ||
private $stream; | ||
|
||
/** @throws \RuntimeException if given `$path` can not be opened in append mode */ | ||
public function __construct(string $path) | ||
{ | ||
$errstr = ''; | ||
\set_error_handler(function (int $_, string $error) use (&$errstr): bool { | ||
// Match errstr from PHP's warning message. | ||
// fopen(/dev/not-a-valid-path): Failed to open stream: Permission denied | ||
$errstr = \preg_replace('#.*: #', '', $error); | ||
|
||
return true; | ||
}); | ||
|
||
$stream = \fopen($path, 'ae'); | ||
\restore_error_handler(); | ||
|
||
if ($stream === false) { | ||
throw new \RuntimeException( | ||
'Unable to open log file "' . $path . '": ' . $errstr | ||
); | ||
} | ||
|
||
$this->stream = $stream; | ||
} | ||
|
||
public function log(string $message): void | ||
{ | ||
$time = \microtime(true); | ||
$prefix = \date('Y-m-d H:i:s', (int) $time) . \sprintf('.%03d ', (int) (($time - (int) $time) * 1e3)); | ||
|
||
$ret = \fwrite($this->stream, $prefix . $message . \PHP_EOL); | ||
assert(\is_int($ret)); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.