Skip to content

Commit

Permalink
Improve logging framework for better debugging
Browse files Browse the repository at this point in the history
Signed-off-by: meenbeese <[email protected]>
  • Loading branch information
meenbeese committed Sep 20, 2023
1 parent 532248b commit 5d5f50d
Show file tree
Hide file tree
Showing 11 changed files with 64 additions and 52 deletions.
7 changes: 5 additions & 2 deletions bin/gen-credits.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@ import 'package:http/http.dart';
import 'package:html/parser.dart';
import 'package:pub_api_client/pub_api_client.dart';
import 'package:pubspec_parse/pubspec_parse.dart';
import 'package:spotube/models/logger.dart';

void main() async {
final logger = getLogger("");

final client = PubClient();

final pubspec = Pubspec.parse(File('pubspec.yaml').readAsStringSync());
Expand Down Expand Up @@ -68,15 +71,15 @@ void main() async {
),
);

print(
logger.d(
packageInfo
.map(
(package) =>
'1. [${package.name}](${package.latestPubspec.homepage ?? package.url}) - ${package.description.replaceAll('\n', '')}',
)
.join('\n'),
);
print(
logger.d(
gitPubspecs.map(
(package) {
final packageUrl = package.homepage ??
Expand Down
5 changes: 4 additions & 1 deletion bin/untranslated_messages.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'dart:convert';
import 'dart:io';
import 'package:spotube/models/logger.dart';

/// Generate JSON output for untranslated messages with English values
/// for quick translation in ChatGPT
Expand All @@ -13,6 +14,8 @@ import 'dart:io';
/// Example: dart bin/untranslated_messages.dart bn
void main(List<String> args) {
final logger = getLogger("");

final file = jsonDecode(
File('untranslated_messages.json').readAsStringSync(),
) as Map<String, dynamic>;
Expand All @@ -35,7 +38,7 @@ void main(List<String> args) {
);
}

print(
logger.d(
const JsonEncoder.withIndent(' ').convert(
args.isNotEmpty ? messagesWithValues[args.first] : messagesWithValues,
),
Expand Down
4 changes: 3 additions & 1 deletion bin/verify-pkgbuild.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import 'dart:convert';
import 'dart:io';
import 'package:spotube/models/logger.dart';

void main() {
final logger = getLogger("");
Process.run("sh", ["-c", '"./scripts/pkgbuild2json.sh aur-struct/PKGBUILD"'])
.then((result) {
try {
Expand All @@ -16,7 +18,7 @@ void main() {
}
} catch (e) {
// ignore: avoid_print
print("[Failed to parse PKGBUILD] $e");
logger.e("[Failed to parse PKGBUILD] $e");
}
});
}
7 changes: 5 additions & 2 deletions lib/extensions/list.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import 'package:collection/collection.dart';
import 'package:spotube/models/logger.dart';

final logger = getLogger("List");

extension MultiSortListMap on List<Map> {
/// [preference] - List of properties in which you want to sort the list
Expand All @@ -18,7 +21,7 @@ extension MultiSortListMap on List<Map> {
return this;
}
if (preference.length != criteria.length) {
print('Criteria length is not equal to preference');
logger.d('Criteria length is not equal to preference');
return this;
}

Expand Down Expand Up @@ -66,7 +69,7 @@ extension MultiSortListTupleMap<V> on List<(Map, V)> {
return this;
}
if (preference.length != criteria.length) {
print('Criteria length is not equal to preference');
logger.d('Criteria length is not equal to preference');
return this;
}

Expand Down
7 changes: 4 additions & 3 deletions lib/models/logger.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ class SpotubeLogger extends Logger {
SpotubeLogger([this.owner]) : super(filter: _SpotubeLogFilter());

@override
void log(Level level, message, [error, StackTrace? stackTrace]) async {
void log(Level level, dynamic message,
{Object? error, StackTrace? stackTrace, DateTime? time}) async {
if (!kIsWeb) {
if (level == Level.error) {
String dir = (await getApplicationDocumentsDirectory()).path;
Expand All @@ -56,15 +57,15 @@ class SpotubeLogger extends Logger {
}
}

super.log(level, "[$owner] $message", error, stackTrace);
super.log(level, "[$owner] $message", error: error, stackTrace: stackTrace);
}
}

class _SpotubeLogFilter extends DevelopmentFilter {
@override
bool shouldLog(LogEvent event) {
if ((logEnv["DEBUG"] == "true" && event.level == Level.debug) ||
(logEnv["VERBOSE"] == "true" && event.level == Level.verbose) ||
(logEnv["VERBOSE"] == "true" && event.level == Level.trace) ||
(logEnv["ERROR"] == "true" && event.level == Level.error)) {
return true;
}
Expand Down
7 changes: 5 additions & 2 deletions lib/provider/proxy_playlist/next_fetcher_mixin.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@ import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:spotify/spotify.dart';
import 'package:spotube/models/local_track.dart';
import 'package:spotube/models/logger.dart';
import 'package:spotube/models/matched_track.dart';
import 'package:spotube/models/spotube_track.dart';
import 'package:spotube/provider/proxy_playlist/proxy_playlist.dart';
import 'package:spotube/provider/user_preferences_provider.dart';
import 'package:spotube/services/supabase.dart';
import 'package:spotube/services/youtube/youtube.dart';

final logger = getLogger("NextFetcherMixin");

mixin NextFetcher on StateNotifier<ProxyPlaylist> {
Future<List<SpotubeTrack>> fetchTracks(
UserPreferences preferences,
Expand Down Expand Up @@ -123,8 +126,8 @@ mixin NextFetcher on StateNotifier<ProxyPlaylist> {
);
}
} catch (e, stackTrace) {
debugPrint(e.toString());
debugPrintStack(stackTrace: stackTrace);
logger.e(e.toString());
logger.t(stackTrace);
}
}
}
2 changes: 1 addition & 1 deletion lib/provider/proxy_playlist/proxy_playlist_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -586,7 +586,7 @@ class ProxyPlaylistNotifier extends PersistedStateNotifier<ProxyPlaylist>
end,
);
}).toList();
getLogger('getSkipSegments').v(
getLogger('getSkipSegments').t(
"[SponsorBlock] successfully fetched skip segments for $id",
);

Expand Down
7 changes: 5 additions & 2 deletions lib/services/download_manager/chunked_download.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:spotube/models/logger.dart';

final logger = getLogger("ChunkedDownload");

/// Downloading by spiting as file in chunks
extension ChunkDownload on Dio {
Expand Down Expand Up @@ -67,11 +70,11 @@ extension ChunkDownload on Dio {
}
await raf.close();

debugPrint("Downloaded file path: ${headFile.path}");
logger.d("Downloaded file path: ${headFile.path}");

headFile = await headFile.rename(savePath);

debugPrint("Renamed file path: ${headFile.path}");
logger.d("Renamed file path: ${headFile.path}");
}

final firstResponse = await downloadChunk(
Expand Down
16 changes: 9 additions & 7 deletions lib/services/download_manager/download_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'package:collection/collection.dart';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:spotube/models/logger.dart';
import 'package:spotube/services/download_manager/chunked_download.dart';
import 'package:spotube/services/download_manager/download_request.dart';
import 'package:spotube/services/download_manager/download_status.dart';
Expand All @@ -22,6 +23,7 @@ typedef DownloadStatusEvent = ({
});

class DownloadManager {
final logger = getLogger("DownloadManager");
final Map<String, DownloadTask> _cache = <String, DownloadTask>{};
final Queue<DownloadRequest> _queue = Queue();
var dio = Dio();
Expand Down Expand Up @@ -73,7 +75,7 @@ class DownloadManager {
}
setStatus(task, DownloadStatus.downloading);

debugPrint("[DownloadManager] $url");
logger.d("[DownloadManager] $url");
final file = File(savePath.toString());
partialFilePath = savePath + partialExtension;
partialFile = File(partialFilePath);
Expand All @@ -82,10 +84,10 @@ class DownloadManager {
final partialFileExist = await partialFile.exists();

if (fileExist) {
debugPrint("[DownloadManager] File Exists");
logger.d("[DownloadManager] File Exists");
setStatus(task, DownloadStatus.completed);
} else if (partialFileExist) {
debugPrint("[DownloadManager] Partial File Exists");
logger.d("[DownloadManager] Partial File Exists");

final partialFileLength = await partialFile.length();

Expand Down Expand Up @@ -205,7 +207,7 @@ class DownloadManager {
}

Future<void> pauseDownload(String url) async {
debugPrint("[DownloadManager] Pause Download");
logger.d("[DownloadManager] Pause Download");
var task = getDownload(url)!;
setStatus(task, DownloadStatus.paused);
task.request.cancelToken.cancel();
Expand All @@ -214,15 +216,15 @@ class DownloadManager {
}

Future<void> cancelDownload(String url) async {
debugPrint("[DownloadManager] Cancel Download");
logger.d("[DownloadManager] Cancel Download");
var task = getDownload(url)!;
setStatus(task, DownloadStatus.canceled);
_queue.remove(task.request);
task.request.cancelToken.cancel();
}

Future<void> resumeDownload(String url) async {
debugPrint("[DownloadManager] Resume Download");
logger.d("[DownloadManager] Resume Download");
var task = getDownload(url)!;
setStatus(task, DownloadStatus.downloading);
task.request.cancelToken = CancelToken();
Expand Down Expand Up @@ -388,7 +390,7 @@ class DownloadManager {

while (_queue.isNotEmpty && runningTasks < maxConcurrentTasks) {
runningTasks++;
debugPrint('Concurrent workers: $runningTasks');
logger.d('Concurrent workers: $runningTasks');
var currentRequest = _queue.removeFirst();

await download(
Expand Down
Loading

0 comments on commit 5d5f50d

Please sign in to comment.