veilid/veilid-flutter/example/lib/log.dart

117 lines
2.7 KiB
Dart
Raw Normal View History

2024-05-02 14:15:42 -04:00
// ignore_for_file: prefer_single_quotes
import 'package:ansicolor/ansicolor.dart';
2022-12-10 12:11:46 -05:00
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
2022-12-10 12:11:46 -05:00
import 'package:loggy/loggy.dart';
import 'package:veilid/veilid.dart';
2022-12-10 12:11:46 -05:00
// Loggy tools
const LogLevel traceLevel = LogLevel('Trace', 1);
VeilidConfigLogLevel convertToVeilidConfigLogLevel(LogLevel? level) {
if (level == null) {
return VeilidConfigLogLevel.off;
}
switch (level) {
case LogLevel.error:
return VeilidConfigLogLevel.error;
case LogLevel.warning:
return VeilidConfigLogLevel.warn;
case LogLevel.info:
return VeilidConfigLogLevel.info;
case LogLevel.debug:
return VeilidConfigLogLevel.debug;
case traceLevel:
return VeilidConfigLogLevel.trace;
}
return VeilidConfigLogLevel.off;
}
String wrapWithLogColor(LogLevel? level, String text) {
if (level == null) {
return text;
}
final pen = AnsiPen();
ansiColorDisabled = false;
switch (level) {
case LogLevel.error:
pen
..reset()
..red(bold: true);
return pen(text);
case LogLevel.warning:
pen
..reset()
..yellow(bold: true);
return pen(text);
case LogLevel.info:
pen
..reset()
..white(bold: true);
return pen(text);
case LogLevel.debug:
pen
..reset()
..green(bold: true);
return pen(text);
case traceLevel:
pen
..reset()
..blue(bold: true);
return pen(text);
}
return text;
}
void setRootLogLevel(LogLevel? level) {
Loggy('').level = getLogOptions(level);
Veilid.instance.changeLogLevel("all", convertToVeilidConfigLogLevel(level));
}
extension PrettyPrintLogRecord on LogRecord {
String pretty() {
final lstr =
wrapWithLogColor(level, '[${level.toString().substring(0, 1)}]');
return '$lstr $message';
}
}
class CallbackPrinter extends LoggyPrinter {
CallbackPrinter() : super();
void Function(LogRecord)? callback;
@override
void onLog(LogRecord record) {
debugPrint(record.pretty());
callback?.call(record);
}
// ignore: use_setters_to_change_properties
void setCallback(void Function(LogRecord)? cb) {
2022-12-10 12:11:46 -05:00
callback = cb;
}
}
CallbackPrinter globalTerminalPrinter = CallbackPrinter();
2022-12-10 12:11:46 -05:00
extension TraceLoggy on Loggy {
void trace(dynamic message, [Object? error, StackTrace? stackTrace]) =>
log(traceLevel, message, error, stackTrace);
}
LogOptions getLogOptions(LogLevel? level) => LogOptions(
level ?? LogLevel.all,
stackTraceLevel: LogLevel.error,
);
2022-12-10 12:11:46 -05:00
void initLoggy() {
Loggy.initLoggy(
logPrinter: globalTerminalPrinter,
logOptions: getLogOptions(null),
);
setRootLogLevel(LogLevel.info);
}