Skip to content

Commit

Permalink
Use log levels when logging to console
Browse files Browse the repository at this point in the history
  • Loading branch information
rolandgeider committed Jan 25, 2025
1 parent ae7ae5d commit 58e7a52
Show file tree
Hide file tree
Showing 13 changed files with 106 additions and 45 deletions.
4 changes: 4 additions & 0 deletions lib/database/exercises/exercise_database.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import 'dart:io';

import 'package:drift/drift.dart';
import 'package:drift/native.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:wger/database/exercises/type_converters.dart';
Expand Down Expand Up @@ -68,6 +69,8 @@ class Equipments extends Table {

@DriftDatabase(tables: [Exercises, Muscles, Equipments, Categories, Languages])
class ExerciseDatabase extends _$ExerciseDatabase {
final _logger = Logger('ExerciseDatabase');

ExerciseDatabase() : super(_openConnection());

// Named constructor for creating in-memory database
Expand Down Expand Up @@ -100,6 +103,7 @@ class ExerciseDatabase extends _$ExerciseDatabase {
Future<void> deleteEverything() {
return transaction(() async {
for (final table in allTables) {
_logger.info('Deleting db cache table ${table.actualTableName}');
await delete(table).go();
}
});
Expand Down
4 changes: 4 additions & 0 deletions lib/database/ingredients/ingredients_database.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import 'dart:io';

import 'package:drift/drift.dart';
import 'package:drift/native.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';

Expand All @@ -21,6 +22,8 @@ class Ingredients extends Table {

@DriftDatabase(tables: [Ingredients])
class IngredientDatabase extends _$IngredientDatabase {
final _logger = Logger('IngredientDatabase');

IngredientDatabase() : super(_openConnection());

// Named constructor for creating in-memory database
Expand Down Expand Up @@ -53,6 +56,7 @@ class IngredientDatabase extends _$IngredientDatabase {
Future<void> deleteEverything() {
return transaction(() async {
for (final table in allTables) {
_logger.info('Deleting db cache table ${table.actualTableName}');
await delete(table).go();
}
});
Expand Down
18 changes: 15 additions & 3 deletions lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:logging/logging.dart';
import 'package:provider/provider.dart';
import 'package:wger/core/locator.dart';
import 'package:wger/providers/add_exercise.dart';
Expand Down Expand Up @@ -55,20 +57,30 @@ import 'package:wger/widgets/core/settings.dart';

import 'providers/auth.dart';

void _setupLogging() {
Logger.root.level = kDebugMode ? Level.ALL : Level.INFO;
Logger.root.onRecord.listen((record) {
print('${record.level.name}: ${record.time} [${record.loggerName}] ${record.message}');
});
}

void main() async {
_setupLogging();
//zx.setLogEnabled(kDebugMode);

// Needs to be called before runApp
WidgetsFlutterBinding.ensureInitialized();

// Locator to initialize exerciseDB
await ServiceLocator().configure();

// Application
runApp(const MyApp());
}

class MyApp extends StatelessWidget {
const MyApp(); // This widget is the root of your application.
const MyApp();

@override
Widget build(BuildContext context) {
return MultiProvider(
Expand Down Expand Up @@ -143,7 +155,7 @@ class MyApp extends StatelessWidget {
highContrastDarkTheme: wgerDarkThemeHc,
themeMode: user.themeMode,
home: auth.isAuth
? const HomeTabsScreen()
? HomeTabsScreen()
: FutureBuilder(
future: auth.tryAutoLogin(),
builder: (ctx, authResultSnapshot) =>
Expand All @@ -156,7 +168,7 @@ class MyApp extends StatelessWidget {
FormScreen.routeName: (ctx) => const FormScreen(),
GalleryScreen.routeName: (ctx) => const GalleryScreen(),
GymModeScreen.routeName: (ctx) => const GymModeScreen(),
HomeTabsScreen.routeName: (ctx) => const HomeTabsScreen(),
HomeTabsScreen.routeName: (ctx) => HomeTabsScreen(),
MeasurementCategoriesScreen.routeName: (ctx) => const MeasurementCategoriesScreen(),
MeasurementEntriesScreen.routeName: (ctx) => const MeasurementEntriesScreen(),
NutritionalPlansScreen.routeName: (ctx) => const NutritionalPlansScreen(),
Expand Down
10 changes: 6 additions & 4 deletions lib/providers/auth.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@

import 'dart:async';
import 'dart:convert';
import 'dart:developer';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:http/http.dart' as http;
import 'package:logging/logging.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:version/version.dart';
Expand All @@ -39,6 +39,8 @@ enum LoginActions {
}

class AuthProvider with ChangeNotifier {
final _logger = Logger('AuthProvider');

String? token;
String? serverUrl;
String? serverVersion;
Expand Down Expand Up @@ -193,15 +195,15 @@ class AuthProvider with ChangeNotifier {
Future<bool> tryAutoLogin() async {
final prefs = await SharedPreferences.getInstance();
if (!prefs.containsKey(PREFS_USER)) {
log('autologin failed');
_logger.info('autologin failed');
return false;
}
final extractedUserData = json.decode(prefs.getString(PREFS_USER)!);

token = extractedUserData['token'];
serverUrl = extractedUserData['serverUrl'];

log('autologin successful');
_logger.info('autologin successful');
setApplicationVersion();
setServerVersion();
notifyListeners();
Expand All @@ -210,7 +212,7 @@ class AuthProvider with ChangeNotifier {
}

Future<void> logout({bool shouldNotify = true}) async {
log('logging out');
_logger.fine('logging out');
token = null;
serverUrl = null;
dataInit = false;
Expand Down
5 changes: 5 additions & 0 deletions lib/providers/body_weight.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,14 @@
*/

import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
import 'package:wger/exceptions/http_exception.dart';
import 'package:wger/models/body_weight/weight_entry.dart';
import 'package:wger/providers/base_provider.dart';

class BodyWeightProvider with ChangeNotifier {
final _logger = Logger('BodyWeightProvider');

final WgerBaseProvider baseProvider;

static const BODY_WEIGHT_URL = 'weightentry';
Expand Down Expand Up @@ -61,6 +64,8 @@ class BodyWeightProvider with ChangeNotifier {
}

Future<List<WeightEntry>> fetchAndSetEntries() async {
_logger.info('Fetching all body weight entries');

// Process the response
final data = await baseProvider.fetchPaginated(baseProvider.makeUrl(
BODY_WEIGHT_URL,
Expand Down
42 changes: 32 additions & 10 deletions lib/providers/exercises.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@

import 'dart:async';
import 'dart:convert';
import 'dart:developer';

import 'package:drift/drift.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wger/core/locator.dart';
import 'package:wger/database/exercises/exercise_database.dart';
Expand All @@ -36,6 +36,8 @@ import 'package:wger/models/exercises/muscle.dart';
import 'package:wger/providers/base_provider.dart';

class ExercisesProvider with ChangeNotifier {
final _logger = Logger('ExercisesProvider');

final WgerBaseProvider baseProvider;
late ExerciseDatabase database;

Expand All @@ -44,7 +46,6 @@ class ExercisesProvider with ChangeNotifier {
}

static const EXERCISE_CACHE_DAYS = 7;
static const EXERCISE_FETCH_HOURS = 4;
static const CACHE_VERSION = 4;

static const exerciseInfoUrlPath = 'exercisebaseinfo';
Expand Down Expand Up @@ -237,13 +238,15 @@ class ExercisesProvider with ChangeNotifier {
}

Future<void> fetchAndSetCategoriesFromApi() async {
_logger.info('Loading exercise categories from API');
final categories = await baseProvider.fetchPaginated(baseProvider.makeUrl(categoriesUrlPath));
for (final category in categories) {
_categories.add(ExerciseCategory.fromJson(category));
}
}

Future<void> fetchAndSetMusclesFromApi() async {
_logger.info('Loading muscles from API');
final muscles = await baseProvider.fetchPaginated(baseProvider.makeUrl(musclesUrlPath));

for (final muscle in muscles) {
Expand All @@ -252,6 +255,7 @@ class ExercisesProvider with ChangeNotifier {
}

Future<void> fetchAndSetEquipmentsFromApi() async {
_logger.info('Loading equipment from API');
final equipments = await baseProvider.fetchPaginated(baseProvider.makeUrl(equipmentUrlPath));

for (final equipment in equipments) {
Expand All @@ -260,6 +264,8 @@ class ExercisesProvider with ChangeNotifier {
}

Future<void> fetchAndSetLanguagesFromApi() async {
_logger.info('Loading languages from API');

final languageData = await baseProvider.fetchPaginated(baseProvider.makeUrl(languageUrlPath));

for (final language in languageData) {
Expand All @@ -271,9 +277,12 @@ class ExercisesProvider with ChangeNotifier {
///
/// If the exercise is not known locally, it is fetched from the server.
Future<Exercise> fetchAndSetExercise(int exerciseId) async {
// _logger.finer('Fetching exercise $exerciseId');
try {
final exercise = findExerciseById(exerciseId);

// _logger.finer('Found $exerciseId in provider list');

// Note: no await since we don't care for the updated data right now. It
// will be written to the db whenever the request finishes and we will get
// the updated exercise the next time
Expand Down Expand Up @@ -312,11 +321,16 @@ class ExercisesProvider with ChangeNotifier {

// Exercise is already known locally
if (exerciseDb != null) {
final nextFetch = exerciseDb.lastFetched.add(const Duration(hours: EXERCISE_FETCH_HOURS));
// _logger.fine('Exercise $exerciseId found in local cache');
final nextFetch = exerciseDb.lastFetched.add(const Duration(days: EXERCISE_CACHE_DAYS));
exercise = Exercise.fromApiDataString(exerciseDb.data, _languages);

// Fetch and update
if (nextFetch.isBefore(DateTime.now())) {
_logger.fine(
'Re-fetching exercise $exerciseId from API since last fetch was ${exerciseDb.lastFetched}',
);

final apiData = await baseProvider.fetch(
baseProvider.makeUrl(exerciseInfoUrlPath, id: exerciseId),
);
Expand All @@ -342,6 +356,7 @@ class ExercisesProvider with ChangeNotifier {
}
// New exercise, fetch and insert to DB
} else {
_logger.fine('New exercise $exerciseId, fetching from API');
final baseData = await baseProvider.fetch(
baseProvider.makeUrl(exerciseInfoUrlPath, id: exerciseId),
);
Expand All @@ -356,6 +371,7 @@ class ExercisesProvider with ChangeNotifier {
lastFetched: DateTime.now(),
),
);
_logger.finer('Saved exercise ${exercise.id!} to db cache');
}
}

Expand Down Expand Up @@ -402,7 +418,8 @@ class ExercisesProvider with ChangeNotifier {
/// - Equipment
/// - Exercises (only local cache)
Future<void> fetchAndSetInitialData() async {
clear();
// clear();
_logger.info('Fetching initial exercise data');

await initCacheTimesLocalPrefs();

Expand All @@ -429,7 +446,7 @@ class ExercisesProvider with ChangeNotifier {
}

final exercisesDb = await database.select(database.exercises).get();
log('Loaded ${exercisesDb.length} exercises from cache');
_logger.info('Loaded ${exercisesDb.length} exercises from DB cache');

exercises = exercisesDb.map((e) => Exercise.fromApiDataString(e.data, _languages)).toList();
}
Expand Down Expand Up @@ -465,7 +482,7 @@ class ExercisesProvider with ChangeNotifier {
final lastUpdateApi = DateTime.parse(exerciseData['last_update_global']);
if (exercise != null && lastUpdateApi.isAfter(exercise.lastUpdate)) {
// TODO: timezones 🥳
print(
_logger.fine(
'Exercise ${exercise.id}: update API $lastUpdateApi | Update DB: ${exercise.lastUpdate}',
);
(database.update(database.exercises)..where((e) => e.id.equals(exerciseData['id']))).write(
Expand Down Expand Up @@ -493,7 +510,7 @@ class ExercisesProvider with ChangeNotifier {

if (muscles.isNotEmpty) {
_muscles = muscles.map((e) => e.data).toList();
log('Loaded ${_muscles.length} muscles from cache');
_logger.info('Loaded ${_muscles.length} muscles from cache');
return;
}
}
Expand All @@ -511,7 +528,7 @@ class ExercisesProvider with ChangeNotifier {
PREFS_LAST_UPDATED_MUSCLES,
validTill.toIso8601String(),
);
log('Wrote ${_muscles.length} muscles from cache. Valid till $validTill');
_logger.fine('Saved ${_muscles.length} muscles to cache (valid till $validTill)');
}

/// Fetches and sets the available categories
Expand All @@ -527,7 +544,7 @@ class ExercisesProvider with ChangeNotifier {

if (categories.isNotEmpty) {
_categories = categories.map((e) => e.data).toList();
log('Loaded ${categories.length} categories from cache');
_logger.info('Loaded ${categories.length} categories from cache');
return;
}
}
Expand All @@ -545,6 +562,7 @@ class ExercisesProvider with ChangeNotifier {
PREFS_LAST_UPDATED_CATEGORIES,
validTill.toIso8601String(),
);
_logger.fine('Saved ${_categories.length} categories to cache (valid till $validTill)');
}

/// Fetches and sets the available languages
Expand All @@ -560,6 +578,7 @@ class ExercisesProvider with ChangeNotifier {

if (languages.isNotEmpty) {
_languages = languages.map((e) => e.data).toList();
_logger.info('Loaded ${languages.length} languages from cache');
return;
}
}
Expand All @@ -572,11 +591,13 @@ class ExercisesProvider with ChangeNotifier {
LanguagesCompanion.insert(id: e.id, data: e),
);
});

validTill = DateTime.now().add(const Duration(days: EXERCISE_CACHE_DAYS));
await prefs.setString(
PREFS_LAST_UPDATED_LANGUAGES,
validTill.toIso8601String(),
);
_logger.info('Saved ${languages.length} languages to cache (valid till $validTill)');
}

/// Fetches and sets the available equipment
Expand All @@ -592,7 +613,7 @@ class ExercisesProvider with ChangeNotifier {

if (equipments.isNotEmpty) {
_equipment = equipments.map((e) => e.data).toList();
log('Loaded ${equipment.length} equipment from cache');
_logger.info('Loaded ${equipment.length} equipment from cache');
return;
}
}
Expand All @@ -610,6 +631,7 @@ class ExercisesProvider with ChangeNotifier {
PREFS_LAST_UPDATED_EQUIPMENT,
validTill.toIso8601String(),
);
_logger.fine('Saved ${_equipment.length} equipment entries to cache (valid till $validTill)');
}

/// Searches for an exercise
Expand Down
Loading

0 comments on commit 58e7a52

Please sign in to comment.