123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157 |
- <?php
- namespace OC\Log;
- use OC\SystemConfig;
- use OCP\ILogger;
- use OCP\Log\IFileBased;
- use OCP\Log\IWriter;
- class File extends LogDetails implements IWriter, IFileBased {
-
- protected $logFile;
-
- protected $logFileMode;
-
- private $config;
- public function __construct(string $path, string $fallbackPath, SystemConfig $config) {
- parent::__construct($config);
- $this->logFile = $path;
- if (!file_exists($this->logFile)) {
- if (
- (
- !is_writable(dirname($this->logFile))
- || !touch($this->logFile)
- )
- && $fallbackPath !== ''
- ) {
- $this->logFile = $fallbackPath;
- }
- }
- $this->config = $config;
- $this->logFileMode = $config->getValue('logfilemode', 0640);
- }
-
- public function write(string $app, $message, int $level) {
- $entry = $this->logDetailsAsJSON($app, $message, $level);
- $handle = @fopen($this->logFile, 'a');
- if ($this->logFileMode > 0 && is_file($this->logFile) && (fileperms($this->logFile) & 0777) != $this->logFileMode) {
- @chmod($this->logFile, $this->logFileMode);
- }
- if ($handle) {
- fwrite($handle, $entry."\n");
- fclose($handle);
- } else {
-
- error_log($entry);
- }
- if (php_sapi_name() === 'cli-server') {
- if (!\is_string($message)) {
- $message = json_encode($message);
- }
- error_log($message, 4);
- }
- }
-
- public function getEntries(int $limit = 50, int $offset = 0):array {
- $minLevel = $this->config->getValue("loglevel", ILogger::WARN);
- $entries = [];
- $handle = @fopen($this->logFile, 'rb');
- if ($handle) {
- fseek($handle, 0, SEEK_END);
- $pos = ftell($handle);
- $line = '';
- $entriesCount = 0;
- $lines = 0;
-
- while ($pos >= 0 && ($limit === null || $entriesCount < $limit)) {
- fseek($handle, $pos);
- $ch = fgetc($handle);
- if ($ch == "\n" || $pos == 0) {
- if ($line != '') {
-
-
- if ($pos == 0) {
- $line = $ch.$line;
- }
- $entry = json_decode($line);
-
- if ($entry->level >= $minLevel) {
- $lines++;
- if ($lines > $offset) {
- $entries[] = $entry;
- $entriesCount++;
- }
- }
- $line = '';
- }
- } else {
- $line = $ch.$line;
- }
- $pos--;
- }
- fclose($handle);
- }
- return $entries;
- }
-
- public function getLogFilePath():string {
- return $this->logFile;
- }
- }
|