Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve and unify the logging framework #738

Merged
merged 2 commits into from
Sep 30, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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("");
meenbeese marked this conversation as resolved.
Show resolved Hide resolved

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("");
meenbeese marked this conversation as resolved.
Show resolved Hide resolved

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("");
meenbeese marked this conversation as resolved.
Show resolved Hide resolved
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
6 changes: 3 additions & 3 deletions pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1226,10 +1226,10 @@ packages:
dependency: "direct main"
description:
name: logger
sha256: "7ad7215c15420a102ec687bb320a7312afd449bac63bfb1c60d9787c27b9767f"
sha256: ba3bc83117b2b49bdd723c0ea7848e8285a0fbc597ba09203b20d329d020c24a
url: "https://pub.dev"
source: hosted
version: "1.4.0"
version: "2.0.2"
logging:
dependency: transitive
description:
Expand Down Expand Up @@ -2286,4 +2286,4 @@ packages:
version: "2.0.2"
sdks:
dart: ">=3.1.0 <4.0.0"
flutter: ">=3.13.0"
flutter: ">=3.13.0"
2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ dependencies:
intl: ^0.18.0
introduction_screen: ^3.0.2
json_annotation: ^4.8.1
logger: ^1.1.0
logger: ^2.0.2
media_kit: ^1.1.3
media_kit_libs_audio: ^1.0.1
metadata_god: ^0.5.0
Expand Down