Skip to content

Commit

Permalink
feat: Logging
Browse files Browse the repository at this point in the history
  • Loading branch information
Gustl22 committed Aug 3, 2024
1 parent 9881390 commit fffac49
Show file tree
Hide file tree
Showing 8 changed files with 50 additions and 21 deletions.
1 change: 1 addition & 0 deletions wrestling_scoreboard_common/analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ include: package:lints/recommended.yaml
linter:
rules:
prefer_relative_imports: true
avoid_print: true


# Needed for freezed package:
Expand Down
1 change: 1 addition & 0 deletions wrestling_scoreboard_common/example/common_example.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@ import 'package:wrestling_scoreboard_common/common.dart';

void main() {
final organization = Organization(name: 'Deutscher Ringer Bund', abbreviation: 'DRB');
// ignore: avoid_print
print('name: ${organization.name}');
}
38 changes: 23 additions & 15 deletions wrestling_scoreboard_common/lib/src/services/apis/germany_by.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import 'dart:convert';
import 'package:collection/collection.dart';
import 'package:country/country.dart';
import 'package:http/http.dart' as http;
import 'package:logging/logging.dart';

import '../../../common.dart';
import '../../util/transaction.dart';
Expand All @@ -17,6 +18,7 @@ import 'mocks/wrestler.json.dart';

class ByGermanyWrestlingApi extends WrestlingApi {
final String apiUrl;
final log = Logger('ByGermanyWrestlingApi');

@override
final BasicAuthService? authService;
Expand Down Expand Up @@ -150,7 +152,7 @@ class ByGermanyWrestlingApi extends WrestlingApi {
if (clubName == null || clubId == null) return null;
if (clubName != clubName.trim()) {
clubName = clubName.trim();
print('Club with club name "$clubName" was trimmed');
log.warning('Club with club name "$clubName" was trimmed');
}
return Club(
name: clubName,
Expand Down Expand Up @@ -233,7 +235,7 @@ class ByGermanyWrestlingApi extends WrestlingApi {
if (teamName == null || teamId == null) return null;
if (teamName != teamName.trim()) {
teamName = teamName.trim();
print('Team with team name "$teamName" was trimmed');
log.warning('Team with team name "$teamName" was trimmed');
}
return Team(
name: teamName,
Expand Down Expand Up @@ -393,8 +395,8 @@ class ByGermanyWrestlingApi extends WrestlingApi {
null => null,
_ => throw UnimplementedError('The bout result type "$result" is not known in bout $boutJson.'),
};
} catch (e) {
print(e);
} catch (e, st) {
log.severe('Could not parse bout result $result', e, st);
}
return null;
}
Expand Down Expand Up @@ -472,7 +474,7 @@ class ByGermanyWrestlingApi extends WrestlingApi {
actionType = BoutActionType.points;
pointCount = int.tryParse(actionStr);
if (pointCount == null) {
throw Exception('Action type "$actionStr" could not be parsed.');
throw Exception('Action type "$actionStr" could not be parsed: $boutJson');
}
}

Expand All @@ -487,13 +489,19 @@ class ByGermanyWrestlingApi extends WrestlingApi {
}

final String boutActionsJson = boutJson['annotation']?['1']?['points']?['value'] ?? '';
final Iterable<BoutAction> boutActions =
boutActionsJson.split(',').where((str) => str.isNotEmpty).map((str) => parseActionStr(str));
final Iterable<BoutAction> boutActions = boutActionsJson.split(',').where((str) => str.isNotEmpty).map((str) {
try {
return parseActionStr(str);
} catch (e, st) {
log.severe('Could not parse action str $str', e, st);
return null;
}
}).whereNotNull();
return MapEntry(bout, boutActions);
}));
return Map.fromEntries(boutActionMapEntries);
} on Exception catch (e) {
print(e);
} on Exception catch (e, st) {
log.severe('Could not import bouts from bout list: $boutListJson', e, st);
return {};
}
}
Expand Down Expand Up @@ -540,7 +548,7 @@ class ByGermanyWrestlingApi extends WrestlingApi {

String body;
if (!isMock) {
print('Call API: $uri');
log.fine('Call API: $uri');
final response = await retry(runAsync: () => http.get(uri));
if (response.statusCode != 200) {
throw Exception(
Expand Down Expand Up @@ -575,7 +583,7 @@ class ByGermanyWrestlingApi extends WrestlingApi {

String body;
if (!isMock) {
print('Call API: $uri');
log.fine('Call API: $uri');
final response = await retry(runAsync: () => http.get(uri));
if (response.statusCode != 200) {
throw Exception(
Expand Down Expand Up @@ -612,7 +620,7 @@ class ByGermanyWrestlingApi extends WrestlingApi {
});
String body;
if (!isMock) {
print('Call API: $uri');
log.fine('Call API: $uri');
final response = await retry(runAsync: () => http.get(uri));
if (response.statusCode != 200) {
throw Exception(
Expand Down Expand Up @@ -655,7 +663,7 @@ class ByGermanyWrestlingApi extends WrestlingApi {

String body;
if (!isMock) {
print('Call API: $uri');
log.fine('Call API: $uri');
final response = await retry(runAsync: () => http.get(uri));
if (response.statusCode != 200) {
throw Exception(
Expand Down Expand Up @@ -696,7 +704,7 @@ class ByGermanyWrestlingApi extends WrestlingApi {

String body;
if (!isMock) {
print('Call API: $uri');
log.fine('Call API: $uri');
final response = await retry(runAsync: () => http.get(uri));
if (response.statusCode != 200) {
throw Exception(
Expand Down Expand Up @@ -743,7 +751,7 @@ class ByGermanyWrestlingApi extends WrestlingApi {
if (authService == null) {
throw Exception('Failed to get the wrestler (passcode: $passCode): No credentials given.');
}
print('Call API: $uri');
log.fine('Call API: $uri');
final response = await retry(runAsync: () => http.get(uri, headers: authService?.header));
if (response.statusCode != 200) {
throw Exception(
Expand Down
14 changes: 9 additions & 5 deletions wrestling_scoreboard_common/lib/src/util/transaction.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import 'dart:async';

import 'package:logging/logging.dart';

Map<String, Completer> _transactionLocks = {};

final log = Logger('Transaction');

Future<T> runSynchronized<T>({
required String key,
bool Function()? canAbort,
Expand All @@ -12,12 +16,12 @@ Future<T> runSynchronized<T>({
try {
completer = await _lockTransaction(key: key, canAbort: canAbort)
.timeout(timeout, onTimeout: () => throw 'Locking for $key took longer than $timeout.');
final result =
await runAsync().timeout(timeout, onTimeout: () => throw 'Async execution for $key took longer than $timeout.');
final result = await runAsync().timeout(timeout,
onTimeout: () => throw 'Async execution in synchronized block for $key took longer than $timeout.');
completer?.complete();
return result;
} catch (error) {
print(error);
log.info(error);
completer?.completeError(error);
rethrow;
} finally {
Expand Down Expand Up @@ -45,14 +49,14 @@ Future<Completer?> _lockTransaction({required String key, bool Function()? canAb
Future<T> retry<T>({
required Future<T> Function() runAsync,
Duration timeout = const Duration(seconds: 5),
int attempts = 5,
int attempts = 10,
}) async {
for (int attempt = 0; attempt < attempts; attempt++) {
try {
return await runAsync()
.timeout(timeout, onTimeout: () => throw 'Async execution took longer than $timeout. Retry ${attempt + 1}');
} catch (error) {
print(error);
log.info(error);
}
}
throw Exception('Final attempt went wrong.');
Expand Down
1 change: 1 addition & 0 deletions wrestling_scoreboard_common/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ dependencies:
country: ^4.1.3
http: ^1.2.1
collection: ^1.18.0
logging: ^1.2.0

dev_dependencies:
build_runner: ^2.3.0
Expand Down
13 changes: 13 additions & 0 deletions wrestling_scoreboard_server/lib/server.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import 'dart:io';

import 'package:dotenv/dotenv.dart' show DotEnv;
import 'package:logging/logging.dart';
import 'package:pubspec_parse/pubspec_parse.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
Expand Down Expand Up @@ -36,6 +37,18 @@ Future init() async {
env.load(); // Load dotenv variables
await _parsePubspec();

// Init logger
Logger.root.level = Level.INFO;
Logger.root.onRecord.listen((record) {
print('[${record.time}] ${record.level.name}: ${record.message}');
if (record.error != null) {
print('Error: ${record.error}');
if (record.stackTrace != null) {
print('StackTrace: ${record.stackTrace}');
}
}
});

// If the "PORT" environment variable is set, listen to it. Otherwise, 8080.
// https://cloud.google.com/run/docs/reference/container-contract#port
final port = int.parse(env['PORT'] ?? '8080');
Expand Down
2 changes: 1 addition & 1 deletion wrestling_scoreboard_server/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ packages:
source: hosted
version: "3.0.0"
logging:
dependency: transitive
dependency: "direct main"
description:
name: logging
sha256: "623a88c9594aa774443aa3eb2d41807a48486b5613e67599fb4c41c0ad47c340"
Expand Down
1 change: 1 addition & 0 deletions wrestling_scoreboard_server/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ dependencies:
shelf_web_socket: ^1.0.3
pubspec_parse: ^1.2.3
collection: ^1.19.0
logging: ^1.2.0

dev_dependencies:
lints: ^3.0.0
Expand Down

0 comments on commit fffac49

Please sign in to comment.