File.php 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. /**
  39. * logging utilities
  40. *
  41. * Log is saved at data/nextcloud.log (on default)
  42. */
  43. class File {
  44. static protected $logFile;
  45. /**
  46. * Init class data
  47. */
  48. public static function init() {
  49. $systemConfig = \OC::$server->getSystemConfig();
  50. $defaultLogFile = $systemConfig->getValue("datadirectory", \OC::$SERVERROOT.'/data').'/nextcloud.log';
  51. self::$logFile = $systemConfig->getValue("logfile", $defaultLogFile);
  52. /**
  53. * Fall back to default log file if specified logfile does not exist
  54. * and can not be created.
  55. */
  56. if (!file_exists(self::$logFile)) {
  57. if(!is_writable(dirname(self::$logFile))) {
  58. self::$logFile = $defaultLogFile;
  59. } else {
  60. if(!touch(self::$logFile)) {
  61. self::$logFile = $defaultLogFile;
  62. }
  63. }
  64. }
  65. }
  66. /**
  67. * write a message in the log
  68. * @param string $app
  69. * @param string $message
  70. * @param int $level
  71. */
  72. public static function write($app, $message, $level) {
  73. $config = \OC::$server->getSystemConfig();
  74. // default to ISO8601
  75. $format = $config->getValue('logdateformat', \DateTime::ATOM);
  76. $logTimeZone = $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($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 = $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(self::$logFile, 'a');
  132. if ((fileperms(self::$logFile) & 0777) != 0640) {
  133. @chmod(self::$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 static function getEntries($limit=50, $offset=0) {
  153. self::init();
  154. $minLevel = \OC::$server->getSystemConfig()->getValue("loglevel", \OCP\Util::WARN);
  155. $entries = array();
  156. $handle = @fopen(self::$logFile, 'rb');
  157. if ($handle) {
  158. fseek($handle, 0, SEEK_END);
  159. $pos = ftell($handle);
  160. $line = '';
  161. $entriesCount = 0;
  162. $lines = 0;
  163. // Loop through each character of the file looking for new lines
  164. while ($pos >= 0 && ($limit === null ||$entriesCount < $limit)) {
  165. fseek($handle, $pos);
  166. $ch = fgetc($handle);
  167. if ($ch == "\n" || $pos == 0) {
  168. if ($line != '') {
  169. // Add the first character if at the start of the file,
  170. // because it doesn't hit the else in the loop
  171. if ($pos == 0) {
  172. $line = $ch.$line;
  173. }
  174. $entry = json_decode($line);
  175. // Add the line as an entry if it is passed the offset and is equal or above the log level
  176. if ($entry->level >= $minLevel) {
  177. $lines++;
  178. if ($lines > $offset) {
  179. $entries[] = $entry;
  180. $entriesCount++;
  181. }
  182. }
  183. $line = '';
  184. }
  185. } else {
  186. $line = $ch.$line;
  187. }
  188. $pos--;
  189. }
  190. fclose($handle);
  191. }
  192. return $entries;
  193. }
  194. /**
  195. * @return string
  196. */
  197. public static function getLogFilePath() {
  198. return self::$logFile;
  199. }
  200. }