super_logging.dart 8.3 KB

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