super_logging.dart 10 KB

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