super_logging.dart 8.9 KB

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