feat(device): TX/RX 日志附加完整 JSON 字符串
This commit is contained in:
49
lib/features/device/services/device_log.dart
Normal file
49
lib/features/device/services/device_log.dart
Normal file
@@ -0,0 +1,49 @@
|
||||
import 'dart:developer' as developer;
|
||||
|
||||
/// 串口/协议层统一日志入口
|
||||
///
|
||||
/// 使用 `dart:developer.log` 便于 Dart DevTools 抓取与分级。
|
||||
/// 所有日志统一以 `kuaishai.device` 为 name 前缀,方便在 DevTools 中过滤。
|
||||
class DeviceLog {
|
||||
static const String _name = 'kuaishai.device';
|
||||
|
||||
/// 信息级别:正常收发与状态变化
|
||||
static void info(String message, {Object? error, Map<String, Object?>? context}) {
|
||||
developer.log(message, name: _name, level: 800, error: error);
|
||||
}
|
||||
|
||||
/// 警告级别:可恢复的异常(解析错误、写入失败等)
|
||||
static void warn(String message, {Object? error, Map<String, Object?>? context}) {
|
||||
developer.log(
|
||||
message,
|
||||
name: _name,
|
||||
level: 900,
|
||||
error: error,
|
||||
// dart:developer 当前不支持直接附带 context;调用方可在 message 中拼接
|
||||
);
|
||||
}
|
||||
|
||||
/// 严重级别:连接断开、协议级不可恢复错误
|
||||
static void severe(String message, {Object? error, Map<String, Object?>? context}) {
|
||||
developer.log(message, name: _name, level: 1000, error: error);
|
||||
}
|
||||
|
||||
/// 将 Map 数据截断为可读摘要,避免在日志中泄露超长负载
|
||||
static String summarizeData(Map<String, dynamic>? data, {int maxKeys = 8}) {
|
||||
if (data == null || data.isEmpty) return '{}';
|
||||
final keys = data.keys.take(maxKeys).toList();
|
||||
final shown = keys.map((k) {
|
||||
final v = data[k];
|
||||
if (v is String) return '$k="${_truncate(v, 32)}"';
|
||||
if (v is List) return '$k=[${v.length}]';
|
||||
return '$k=$v';
|
||||
}).join(', ');
|
||||
final suffix = data.length > maxKeys ? ', ...' : '';
|
||||
return '{$shown$suffix}';
|
||||
}
|
||||
|
||||
static String _truncate(String s, int max) {
|
||||
if (s.length <= max) return s;
|
||||
return '${s.substring(0, max)}…';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user