Skip to content

Commit

Permalink
Added setting to change log level (#192)
Browse files Browse the repository at this point in the history
  • Loading branch information
Gold872 authored Jan 22, 2025
1 parent b94b099 commit 9dcd004
Show file tree
Hide file tree
Showing 11 changed files with 479 additions and 263 deletions.
8 changes: 7 additions & 1 deletion lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'package:flutter/material.dart';
import 'package:collection/collection.dart';
import 'package:dot_cast/dot_cast.dart';
import 'package:flex_seed_scheme/flex_seed_scheme.dart';
import 'package:logger/logger.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:screen_retriever/screen_retriever.dart';
Expand Down Expand Up @@ -53,6 +54,11 @@ void main() async {
preferences = await SharedPreferences.getInstance();
}

Level logLevel = Settings.logLevels.firstWhereOrNull((level) =>
level.levelName == preferences.getString(PrefKeys.logLevel)) ??
Defaults.logLevel;
Logger.level = logLevel;

await windowManager.ensureInitialized();

NTWidgetBuilder.ensureInitialized();
Expand Down Expand Up @@ -143,7 +149,7 @@ Future<void> _backupPreferences(String appFolderPath) async {
if (await File(backup).exists()) await File(backup).delete(recursive: true);
await File(original).copy(backup);

logger.info('Backup up shared_preferences.json to $backup');
logger.info('Backed up shared_preferences.json to $backup');
} catch (_) {
/* Do nothing */
}
Expand Down
15 changes: 15 additions & 0 deletions lib/pages/dashboard_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import 'package:elegant_notification/resources/stacked_options.dart';
import 'package:file_selector/file_selector.dart';
import 'package:flex_seed_scheme/flex_seed_scheme.dart';
import 'package:http/http.dart';
import 'package:logger/logger.dart';
import 'package:path/path.dart' as path;
import 'package:popover/popover.dart';
import 'package:screen_retriever/screen_retriever.dart';
Expand Down Expand Up @@ -1627,6 +1628,17 @@ class _DashboardPageState extends State<DashboardPage> with WindowListener {
},
onColorChanged: widget.onColorChanged,
onThemeVariantChanged: widget.onThemeVariantChanged,
onLogLevelChanged: (level) async {
if (level == null) {
logger.info('Removing log level preference');
await preferences.remove(PrefKeys.logLevel);
Logger.level = Defaults.logLevel;
return;
}
logger.info('Changing log level to ${level.levelName}');
Logger.level = level;
await preferences.setString(PrefKeys.logLevel, level.levelName);
},
onGridDPIChanged: (value) async {
if (value == null) {
return;
Expand All @@ -1636,9 +1648,11 @@ class _DashboardPageState extends State<DashboardPage> with WindowListener {
return;
}
if (dpiOverride != null) {
logger.info('Setting DPI override to ${dpiOverride.toDouble()}');
await preferences.setDouble(
PrefKeys.gridDpiOverride, dpiOverride.toDouble());
} else {
logger.info('Removing DPI override preference');
await preferences.remove(PrefKeys.gridDpiOverride);
}
setState(() {});
Expand All @@ -1647,6 +1661,7 @@ class _DashboardPageState extends State<DashboardPage> with WindowListener {
Uri uri = Uri.file(
'${path.dirname(Platform.resolvedExecutable)}/data/flutter_assets/assets/');
if (await canLaunchUrl(uri)) {
logger.info('Opening URL (assets folder): ${uri.toString()}');
launchUrl(uri);
}
},
Expand Down
2 changes: 2 additions & 0 deletions lib/services/ds_interop.dart
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ class DSInteropClient {
}

void _tcpSocketOnMessage(String data) {
logger.debug('Received data from TCP 1742: "$data"');
var jsonData = jsonDecode(data.toString());

if (jsonData is! Map) {
Expand Down Expand Up @@ -140,6 +141,7 @@ class DSInteropClient {
}

void _dbModeServerOnMessage(Uint8List data) {
logger.trace('Received message from socket on TCP 1741: $data');
_tcpBuffer.addAll(data);
Map<int, Uint8List> mappedData = {};

Expand Down
6 changes: 5 additions & 1 deletion lib/services/field_images.dart
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ class FieldImages {
return fields.map((e) => e.game).contains(game);
}

static Future loadFields(String directory) async {
static Future<void> loadFields(String directory) async {
logger.info('Loading fields');
AssetManifest assetManifest =
await AssetManifest.loadFromAssetBundle(rootBundle);

Expand All @@ -49,6 +50,7 @@ class FieldImages {
}

static Future loadField(String filePath) async {
logger.trace('Loading field at $filePath');
String jsonString = await rootBundle.loadString(filePath);

Map<String, dynamic> jsonData = jsonDecode(jsonString);
Expand Down Expand Up @@ -121,13 +123,15 @@ class Field {
}

void loadFieldImage() {
logger.debug('Loading field image for $game');
fieldImage = Image.asset(
jsonData['field-image'],
fit: BoxFit.contain,
);
fieldImage.image
.resolve(ImageConfiguration.empty)
.addListener(ImageStreamListener((image, synchronousCall) {
logger.trace('Initializing image width and height for $game');
fieldImageWidth = image.image.width;
fieldImageHeight = image.image.height;

Expand Down
4 changes: 3 additions & 1 deletion lib/services/log.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,14 @@ class Log {
ConsoleOutput(),
if (kReleaseMode) FileOutput(file: logFile),
]),
level: kDebugMode ? Level.debug : Level.info,
filter: ProductionFilter(),
);
}

void log(Level level, dynamic message, [dynamic error, StackTrace? trace]) {
if (Logger.level.value > level.value) {
return;
}
_logger?.log(
level,
'[${_dateFormat.format(DateTime.now())}]: $message',
Expand Down
35 changes: 33 additions & 2 deletions lib/services/nt4_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ class NT4Subscription extends ValueNotifier<Object?> {
this.uid = -1,
}) : super(null);

@override
String toString() {
return 'NT4Subscription(Topic: $topic, Options: $options, Uid: $uid)';
}

void listen(Function(Object?, int) onChanged) {
_listeners.add(onChanged);
}
Expand Down Expand Up @@ -122,6 +127,8 @@ class NT4Subscription extends ValueNotifier<Object?> {
}

void updateValue(Object? value, int timestamp) {
logger.trace(
'Updating value for subscription: $this - Value: $value, Time: $timestamp');
for (var listener in _listeners) {
listener(value, timestamp);
}
Expand Down Expand Up @@ -189,6 +196,11 @@ class NT4SubscriptionOptions {
@override
int get hashCode =>
Object.hashAll([periodicRateSeconds, all, topicsOnly, prefix]);

@override
String toString() {
return 'NT4SubscriptionOptions(Periodic: $periodicRateSeconds, All: $all, TopicsOnly: $topicsOnly, Prefix: $prefix)';
}
}

class NT4Topic {
Expand All @@ -206,6 +218,11 @@ class NT4Topic {
required this.properties,
});

@override
String toString() {
return 'NT4Topic(Name: $name, Type: $type, ID: $id, PubUID: $pubUID, Properties: $properties)';
}

Map<String, dynamic> toPublishJson() {
return {
'name': name,
Expand Down Expand Up @@ -351,6 +368,8 @@ class NT4Client {
options: options,
);

logger.trace('Creating new subscription: $newSub');

_subscriptions[newSub.uid] = newSub;
_subscribedTopics.add(newSub);
_wsSubscribe(newSub);
Expand All @@ -365,6 +384,7 @@ class NT4Client {
}

void unSubscribe(NT4Subscription sub) {
logger.trace('Unsubscribing: $sub');
_subscriptions.remove(sub.uid);
_subscribedTopics.remove(sub);
_wsUnsubscribe(sub);
Expand Down Expand Up @@ -392,6 +412,8 @@ class NT4Client {
}

void setProperties(NT4Topic topic, bool isPersistent, bool isRetained) {
logger.trace(
'Updating properties - Topic: $topic, Persistent: $isPersistent, Retained: $isRetained');
topic.properties['persistent'] = isPersistent;
topic.properties['retained'] = isRetained;
_wsSetProperties(topic);
Expand All @@ -416,20 +438,25 @@ class NT4Client {
topic.pubUID = _clientPublishedTopics[topic.name]!.pubUID;
return;
}
logger.trace('Publishing topic: $topic');

topic.pubUID = getNewPubUID();
_clientPublishedTopics[topic.name] = topic;
_wsPublish(topic);
}

void unpublishTopic(NT4Topic topic) {
logger.trace('Unpublishing topic: $topic');
_clientPublishedTopics.remove(topic.name);
_wsUnpublish(topic);
}

void addSample(NT4Topic topic, dynamic data, [int? timestamp]) {
timestamp ??= getServerTimeUS();

logger.trace(
'Adding sample - Topic: $topic, Data: $data, Timestamp: $timestamp');

_wsSendBinary(
serialize([topic.pubUID, timestamp, topic.getTypeId(), data]));

Expand Down Expand Up @@ -465,8 +492,10 @@ class NT4Client {
if (timeTopic != null) {
int timeToSend = _getClientTimeUS();

var rawData =
serialize([timeTopic.pubUID, 0, timeTopic.getTypeId(), timeToSend]);
var rttValue = [timeTopic.pubUID, 0, timeTopic.getTypeId(), timeToSend];
var rawData = serialize(rttValue);

logger.trace('Sending RTT timestamp: $rttValue');

if (_useRTT) {
if (rttWebsocketActive && mainWebsocketActive) {
Expand All @@ -479,6 +508,8 @@ class NT4Client {
}

void _rttHandleRecieveTimestamp(int serverTimestamp, int clientTimestamp) {
logger.trace(
'RTT Received - Server Time: $serverTimestamp, Client Time: $clientTimestamp');
int rxTime = _getClientTimeUS();

int rtt = rxTime - clientTimestamp;
Expand Down
24 changes: 23 additions & 1 deletion lib/services/settings.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,24 @@
import 'package:flutter/foundation.dart';

import 'package:flex_seed_scheme/flex_seed_scheme.dart';
import 'package:logger/logger.dart';

import 'package:elastic_dashboard/services/ip_address_util.dart';

extension LogLevelUtil on Level {
String get levelName => switch (this) {
Level.all => 'All',
Level.trace => 'Trace',
Level.debug => 'Debug',
Level.info => 'Info',
Level.warning => 'Warning',
Level.error => 'Error',
Level.fatal => 'Fatal',
Level.off => 'Off',
_ => 'Unknown',
};
}

class Settings {
static const String repositoryLink =
'https://github.com/Gold872/elastic-dashboard';
Expand All @@ -11,6 +28,9 @@ class Settings {
// disable on some platforms, this is a dumb workaround for it
static bool isWindowDraggable = true;
static bool isWindowMaximizable = true;

static final List<Level> logLevels =
Level.values.where((level) => level.value % 1000 == 0).toList();
}

class Defaults {
Expand All @@ -19,6 +39,8 @@ class Defaults {
static FlexSchemeVariant themeVariant = FlexSchemeVariant.material3Legacy;

static const String defaultVariantName = 'Material-3 Legacy (Default)';
static const String defaultLogLevelName = 'Automatic';
static const Level logLevel = kDebugMode ? Level.debug : Level.info;
static const String ipAddress = '127.0.0.1';

static const int teamNumber = 9999;
Expand Down Expand Up @@ -49,7 +71,7 @@ class PrefKeys {
static String rememberWindowPosition = 'remember_window_position';
static String defaultPeriod = 'default_period';
static String defaultGraphPeriod = 'default_graph_period';
static String logLevel = 'log_level';
static String gridDpiOverride = 'grid_dpi_override';
static String showOpenAssetsFolderWarning = "show_assets_folder_warning";
static String windowPosition = 'window_position';
}
Loading

0 comments on commit 9dcd004

Please sign in to comment.