1
0

File.php 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Andreas Fischer <bantu@owncloud.com>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author duritong <peter.meier+github@immerda.ch>
  8. * @author Georg Ehrke <oc.list@georgehrke.com>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Juan Pablo Villafáñez <jvillafanez@solidgear.es>
  11. * @author Lukas Reschke <lukas@statuscode.ch>
  12. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  13. * @author Morris Jobke <hey@morrisjobke.de>
  14. * @author Phiber2000 <phiber2000@gmx.de>
  15. * @author Robin Appelman <robin@icewind.nl>
  16. * @author Roeland Jago Douma <roeland@famdouma.nl>
  17. * @author Roger Szabo <roger.szabo@web.de>
  18. * @author Thomas Müller <thomas.mueller@tmit.eu>
  19. * @author Thomas Pulzer <t.pulzer@kniel.de>
  20. * @author Vincent Petry <pvince81@owncloud.com>
  21. *
  22. * @license AGPL-3.0
  23. *
  24. * This code is free software: you can redistribute it and/or modify
  25. * it under the terms of the GNU Affero General Public License, version 3,
  26. * as published by the Free Software Foundation.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU Affero General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU Affero General Public License, version 3,
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>
  35. *
  36. */
  37. namespace OC\Log;
  38. use OC\SystemConfig;
  39. use OCP\Log\IFileBased;
  40. use OCP\Log\IWriter;
  41. use OCP\ILogger;
  42. /**
  43. * logging utilities
  44. *
  45. * Log is saved at data/nextcloud.log (on default)
  46. */
  47. class File implements IWriter, IFileBased {
  48. /** @var string */
  49. protected $logFile;
  50. /** @var SystemConfig */
  51. private $config;
  52. public function __construct(string $path, string $fallbackPath = '', SystemConfig $config) {
  53. $this->logFile = $path;
  54. if (!file_exists($this->logFile)) {
  55. if(
  56. (
  57. !is_writable(dirname($this->logFile))
  58. || !touch($this->logFile)
  59. )
  60. && $fallbackPath !== ''
  61. ) {
  62. $this->logFile = $fallbackPath;
  63. }
  64. }
  65. $this->config = $config;
  66. }
  67. /**
  68. * write a message in the log
  69. * @param string $app
  70. * @param string|array $message
  71. * @param int $level
  72. */
  73. public function write(string $app, $message, int $level) {
  74. // default to ISO8601
  75. $format = $this->config->getValue('logdateformat', \DateTime::ATOM);
  76. $logTimeZone = $this->config->getValue('logtimezone', 'UTC');
  77. try {
  78. $timezone = new \DateTimeZone($logTimeZone);
  79. } catch (\Exception $e) {
  80. $timezone = new \DateTimeZone('UTC');
  81. }
  82. $time = \DateTime::createFromFormat("U.u", number_format(microtime(true), 4, ".", ""));
  83. if ($time === false) {
  84. $time = new \DateTime(null, $timezone);
  85. } else {
  86. // apply timezone if $time is created from UNIX timestamp
  87. $time->setTimezone($timezone);
  88. }
  89. $request = \OC::$server->getRequest();
  90. $reqId = $request->getId();
  91. $remoteAddr = $request->getRemoteAddress();
  92. // remove username/passwords from URLs before writing the to the log file
  93. $time = $time->format($format);
  94. $url = ($request->getRequestUri() !== '') ? $request->getRequestUri() : '--';
  95. $method = is_string($request->getMethod()) ? $request->getMethod() : '--';
  96. if($this->config->getValue('installed', false)) {
  97. $user = \OC_User::getUser() ? \OC_User::getUser() : '--';
  98. } else {
  99. $user = '--';
  100. }
  101. $userAgent = $request->getHeader('User-Agent');
  102. if ($userAgent === '') {
  103. $userAgent = '--';
  104. }
  105. $version = $this->config->getValue('version', '');
  106. $entry = compact(
  107. 'reqId',
  108. 'level',
  109. 'time',
  110. 'remoteAddr',
  111. 'user',
  112. 'app',
  113. 'method',
  114. 'url',
  115. 'message',
  116. 'userAgent',
  117. 'version'
  118. );
  119. // PHP's json_encode only accept proper UTF-8 strings, loop over all
  120. // elements to ensure that they are properly UTF-8 compliant or convert
  121. // them manually.
  122. foreach($entry as $key => $value) {
  123. if(is_string($value)) {
  124. $testEncode = json_encode($value);
  125. if($testEncode === false) {
  126. $entry[$key] = utf8_encode($value);
  127. }
  128. }
  129. }
  130. $entry = json_encode($entry, JSON_PARTIAL_OUTPUT_ON_ERROR);
  131. $handle = @fopen($this->logFile, 'a');
  132. if ((fileperms($this->logFile) & 0777) != 0640) {
  133. @chmod($this->logFile, 0640);
  134. }
  135. if ($handle) {
  136. fwrite($handle, $entry."\n");
  137. fclose($handle);
  138. } else {
  139. // Fall back to error_log
  140. error_log($entry);
  141. }
  142. if (php_sapi_name() === 'cli-server') {
  143. error_log($message, 4);
  144. }
  145. }
  146. /**
  147. * get entries from the log in reverse chronological order
  148. * @param int $limit
  149. * @param int $offset
  150. * @return array
  151. */
  152. public function getEntries(int $limit=50, int $offset=0):array {
  153. $minLevel = $this->config->getValue("loglevel", ILogger::WARN);
  154. $entries = array();
  155. $handle = @fopen($this->logFile, 'rb');
  156. if ($handle) {
  157. fseek($handle, 0, SEEK_END);
  158. $pos = ftell($handle);
  159. $line = '';
  160. $entriesCount = 0;
  161. $lines = 0;
  162. // Loop through each character of the file looking for new lines
  163. while ($pos >= 0 && ($limit === null ||$entriesCount < $limit)) {
  164. fseek($handle, $pos);
  165. $ch = fgetc($handle);
  166. if ($ch == "\n" || $pos == 0) {
  167. if ($line != '') {
  168. // Add the first character if at the start of the file,
  169. // because it doesn't hit the else in the loop
  170. if ($pos == 0) {
  171. $line = $ch.$line;
  172. }
  173. $entry = json_decode($line);
  174. // Add the line as an entry if it is passed the offset and is equal or above the log level
  175. if ($entry->level >= $minLevel) {
  176. $lines++;
  177. if ($lines > $offset) {
  178. $entries[] = $entry;
  179. $entriesCount++;
  180. }
  181. }
  182. $line = '';
  183. }
  184. } else {
  185. $line = $ch.$line;
  186. }
  187. $pos--;
  188. }
  189. fclose($handle);
  190. }
  191. return $entries;
  192. }
  193. /**
  194. * @return string
  195. */
  196. public function getLogFilePath():string {
  197. return $this->logFile;
  198. }
  199. }