super_logging.dart 8.6 KB

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