super_logging.dart 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. // @dart=2.9
  2. library super_logging;
  3. import 'dart:async';
  4. import 'dart:collection';
  5. import 'dart:core';
  6. import 'dart:io';
  7. import 'package:flutter/foundation.dart';
  8. import 'package:flutter/widgets.dart';
  9. import 'package:http/http.dart' as http;
  10. import 'package:intl/intl.dart';
  11. import 'package:logging/logging.dart';
  12. import 'package:package_info_plus/package_info_plus.dart';
  13. import 'package:path/path.dart';
  14. import 'package:path_provider/path_provider.dart';
  15. import 'package:photos/core/error-reporting/tunneled_transport.dart';
  16. import 'package:sentry_flutter/sentry_flutter.dart';
  17. typedef FutureOrVoidCallback = FutureOr<void> Function();
  18. extension SuperString on String {
  19. Iterable<String> chunked(int chunkSize) sync* {
  20. var start = 0;
  21. while (true) {
  22. final stop = start + chunkSize;
  23. if (stop > length) break;
  24. yield substring(start, stop);
  25. start = stop;
  26. }
  27. if (start < length) {
  28. yield substring(start);
  29. }
  30. }
  31. }
  32. extension SuperLogRecord on LogRecord {
  33. String toPrettyString([String extraLines]) {
  34. final header = "[$loggerName] [$level] [$time]";
  35. var msg = "$header $message";
  36. if (error != null) {
  37. msg += "\n⤷ type: ${error.runtimeType}\n⤷ error: $error";
  38. }
  39. if (stackTrace != null) {
  40. msg += "\n⤷ trace: $stackTrace";
  41. }
  42. for (var line in extraLines?.split('\n') ?? []) {
  43. msg += '\n$header $line';
  44. }
  45. return msg;
  46. }
  47. }
  48. class LogConfig {
  49. /// The DSN for a Sentry app.
  50. /// This can be obtained from the Sentry apps's "settings > Client Keys (DSN)" page.
  51. ///
  52. /// Only logs containing errors are sent to sentry.
  53. /// Errors can be caught using a try-catch block, like so:
  54. ///
  55. /// ```
  56. /// final logger = Logger("main");
  57. ///
  58. /// try {
  59. /// // do something dangerous here
  60. /// } catch(e, trace) {
  61. /// logger.info("Huston, we have a problem", e, trace);
  62. /// }
  63. /// ```
  64. ///
  65. /// If this is [null], Sentry logger is completely disabled (default).
  66. String sentryDsn;
  67. String tunnel;
  68. /// A built-in retry mechanism for sending errors to sentry.
  69. ///
  70. /// This parameter defines the time to wait for, before retrying.
  71. Duration sentryRetryDelay;
  72. /// Path of the directory where log files will be stored.
  73. ///
  74. /// If this is [null], file logging is completely disabled (default).
  75. ///
  76. /// If this is an empty string (['']),
  77. /// then a 'logs' directory will be created in [getTemporaryDirectory()].
  78. ///
  79. /// A non-empty string will be treated as an explicit path to a directory.
  80. ///
  81. /// The chosen directory can be accessed using [SuperLogging.logFile.parent].
  82. String logDirPath;
  83. /// The maximum number of log files inside [logDirPath].
  84. ///
  85. /// One log file is created per day.
  86. /// Older log files are deleted automatically.
  87. int maxLogFiles;
  88. /// Whether to enable super logging features in debug mode.
  89. ///
  90. /// Sentry and file logging are typically not needed in debug mode,
  91. /// where a complete logcat is available.
  92. bool enableInDebugMode;
  93. /// If provided, super logging will invoke this function, and
  94. /// any uncaught errors during its execution will be reported.
  95. ///
  96. /// Works by using [FlutterError.onError] and [runZoned].
  97. FutureOrVoidCallback body;
  98. /// The date format for storing log files.
  99. ///
  100. /// `DateFormat('y-M-d')` by default.
  101. DateFormat dateFmt;
  102. String prefix;
  103. LogConfig({
  104. this.sentryDsn,
  105. this.tunnel,
  106. this.sentryRetryDelay = const Duration(seconds: 30),
  107. this.logDirPath,
  108. this.maxLogFiles = 10,
  109. this.enableInDebugMode = false,
  110. this.body,
  111. this.dateFmt,
  112. this.prefix = "",
  113. }) {
  114. dateFmt ??= DateFormat("y-M-d");
  115. }
  116. }
  117. class SuperLogging {
  118. /// The logger for SuperLogging
  119. static final $ = Logger('ente_logging');
  120. /// The current super logging configuration
  121. static LogConfig config;
  122. static Future<void> main([LogConfig config]) async {
  123. config ??= LogConfig();
  124. SuperLogging.config = config;
  125. WidgetsFlutterBinding.ensureInitialized();
  126. appVersion ??= await getAppVersion();
  127. final isFDroidClient = await isFDroidBuild();
  128. if (isFDroidClient) {
  129. config.sentryDsn = null;
  130. config.tunnel = null;
  131. }
  132. final enable = config.enableInDebugMode || kReleaseMode;
  133. sentryIsEnabled = enable && config.sentryDsn != null && !isFDroidClient;
  134. fileIsEnabled = enable && config.logDirPath != null;
  135. if (fileIsEnabled) {
  136. await setupLogDir();
  137. }
  138. if (sentryIsEnabled) {
  139. setupSentry();
  140. }
  141. Logger.root.level = Level.ALL;
  142. Logger.root.onRecord.listen(onLogRecord);
  143. if (isFDroidClient) {
  144. assert(
  145. sentryIsEnabled == false,
  146. "sentry dsn should be disabled for "
  147. "f-droid config ${config.sentryDsn} & ${config.tunnel}",
  148. );
  149. }
  150. if (!enable) {
  151. $.info("detected debug mode; sentry & file logging disabled.");
  152. }
  153. if (fileIsEnabled) {
  154. $.info("log file for today: $logFile with prefix ${config.prefix}");
  155. }
  156. if (sentryIsEnabled) {
  157. $.info("sentry uploader started");
  158. }
  159. if (config.body == null) return;
  160. if (enable && sentryIsEnabled) {
  161. await SentryFlutter.init(
  162. (options) {
  163. options.dsn = config.sentryDsn;
  164. options.httpClient = http.Client();
  165. if (config.tunnel != null) {
  166. options.transport =
  167. TunneledTransport(Uri.parse(config.tunnel), options);
  168. }
  169. },
  170. appRunner: () => config.body(),
  171. );
  172. } else {
  173. await config.body();
  174. }
  175. }
  176. static void setUserID(String userID) async {
  177. if (config?.sentryDsn != null) {
  178. Sentry.configureScope((scope) => scope.user = SentryUser(id: userID));
  179. $.info("setting sentry user ID to: $userID");
  180. }
  181. }
  182. static Future<void> _sendErrorToSentry(Object error, StackTrace stack) async {
  183. try {
  184. await Sentry.captureException(
  185. error,
  186. stackTrace: stack,
  187. );
  188. } catch (e) {
  189. $.info('Sending report to sentry.io failed: $e');
  190. $.info('Original error: $error');
  191. }
  192. }
  193. static String _lastExtraLines = '';
  194. static Future onLogRecord(LogRecord rec) async {
  195. // log misc info if it changed
  196. String extraLines = "app version: '$appVersion'\n";
  197. if (extraLines != _lastExtraLines) {
  198. _lastExtraLines = extraLines;
  199. } else {
  200. extraLines = null;
  201. }
  202. final str = config.prefix + " " + rec.toPrettyString(extraLines);
  203. // write to stdout
  204. printLog(str);
  205. // push to log queue
  206. if (fileIsEnabled) {
  207. fileQueueEntries.add(str + '\n');
  208. if (fileQueueEntries.length == 1) {
  209. flushQueue();
  210. }
  211. }
  212. // add error to sentry queue
  213. if (sentryIsEnabled && rec.error != null) {
  214. _sendErrorToSentry(rec.error, null);
  215. }
  216. }
  217. static final Queue<String> fileQueueEntries = Queue();
  218. static bool isFlushing = false;
  219. static void flushQueue() async {
  220. if (isFlushing) {
  221. return;
  222. }
  223. isFlushing = true;
  224. final entry = fileQueueEntries.removeFirst();
  225. await logFile.writeAsString(entry, mode: FileMode.append, flush: true);
  226. isFlushing = false;
  227. if (fileQueueEntries.isNotEmpty) {
  228. flushQueue();
  229. }
  230. }
  231. // Logs on must be chunked or they get truncated otherwise
  232. // See https://github.com/flutter/flutter/issues/22665
  233. static var logChunkSize = 800;
  234. static void printLog(String text) {
  235. text.chunked(logChunkSize).forEach(print);
  236. }
  237. /// A queue to be consumed by [setupSentry].
  238. static final sentryQueueControl = StreamController<Error>();
  239. /// Whether sentry logging is currently enabled or not.
  240. static bool sentryIsEnabled;
  241. static Future<void> setupSentry() async {
  242. await for (final error in sentryQueueControl.stream.asBroadcastStream()) {
  243. try {
  244. Sentry.captureException(
  245. error,
  246. );
  247. } catch (e) {
  248. $.fine(
  249. "sentry upload failed; will retry after ${config.sentryRetryDelay}",
  250. );
  251. doSentryRetry(error);
  252. }
  253. }
  254. }
  255. static void doSentryRetry(Error error) async {
  256. await Future.delayed(config.sentryRetryDelay);
  257. sentryQueueControl.add(error);
  258. }
  259. /// The log file currently in use.
  260. static File logFile;
  261. /// Whether file logging is currently enabled or not.
  262. static bool fileIsEnabled;
  263. static Future<void> setupLogDir() async {
  264. var dirPath = config.logDirPath;
  265. // choose [logDir]
  266. if (dirPath.isEmpty) {
  267. final root = await getExternalStorageDirectory();
  268. dirPath = '${root.path}/logs';
  269. }
  270. // create [logDir]
  271. final dir = Directory(dirPath);
  272. await dir.create(recursive: true);
  273. final files = <File>[];
  274. final dates = <File, DateTime>{};
  275. // collect all log files with valid names
  276. await for (final file in dir.list()) {
  277. try {
  278. final date = config.dateFmt.parse(basename(file.path));
  279. dates[file as File] = date;
  280. files.add(file);
  281. } on FormatException {}
  282. }
  283. // delete old log files, if [maxLogFiles] is exceeded.
  284. if (files.length > config.maxLogFiles) {
  285. // sort files based on ascending order of date (older first)
  286. files.sort((a, b) => dates[a].compareTo(dates[b]));
  287. final extra = files.length - config.maxLogFiles;
  288. final toDelete = files.sublist(0, extra);
  289. for (final file in toDelete) {
  290. try {
  291. $.fine(
  292. "deleting log file ${file.path}",
  293. );
  294. await file.delete();
  295. } catch (ignore) {}
  296. }
  297. }
  298. logFile = File("$dirPath/${config.dateFmt.format(DateTime.now())}.txt");
  299. }
  300. /// Current app version, obtained from package_info plugin.
  301. ///
  302. /// See: [getAppVersion]
  303. static String appVersion;
  304. static Future<String> getAppVersion() async {
  305. final pkgInfo = await PackageInfo.fromPlatform();
  306. return "${pkgInfo.version}+${pkgInfo.buildNumber}";
  307. }
  308. // disable sentry on f-droid. We need to make it opt-in preference
  309. static Future<bool> isFDroidBuild() async {
  310. if (!Platform.isAndroid) {
  311. return false;
  312. }
  313. final pkgName = (await PackageInfo.fromPlatform()).packageName;
  314. return pkgName.startsWith("io.ente.photos.fdroid");
  315. }
  316. }