111 lines
2.6 KiB
Dart
111 lines
2.6 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
import 'dart:io';
|
|
|
|
import 'package:common_utils/common_utils.dart';
|
|
import 'package:logger/logger.dart';
|
|
|
|
import 'package:pj_supermarket_cloud/common/index.dart';
|
|
|
|
final logger = Logger(
|
|
filter: AppLogFilter(),
|
|
printer: customPrinter,
|
|
output: ConsoleOutput(),
|
|
);
|
|
final customPrinter = PrettyPrinter(
|
|
lineLength: 0,
|
|
methodCount: 1,
|
|
errorMethodCount: 1,
|
|
colors: true,
|
|
printEmojis: false,
|
|
printTime: true,
|
|
noBoxingByDefault: true,
|
|
);
|
|
|
|
class AppLogFilter extends LogFilter {
|
|
@override
|
|
bool shouldLog(LogEvent event) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
class ConsoleOutput extends LogOutput {
|
|
String? _filePath;
|
|
IOSink? _sink;
|
|
Timer? _timer;
|
|
Future<void> _queue = Future.value();
|
|
|
|
Future<void> _enqueue(Future<void> Function() action) {
|
|
_queue = _queue.then((_) => action()).catchError((e, stack) {
|
|
print("写入日志错误error:|$e|stack:|$stack|");
|
|
});
|
|
return _queue;
|
|
}
|
|
|
|
@override
|
|
Future<void> init() async {
|
|
try {
|
|
await _enqueue(() async {
|
|
await _sink?.flush();
|
|
await _sink?.close();
|
|
_filePath = await AppFileTool.getLoggerBackupPath();
|
|
if (ObjectUtil.isNotEmpty(_filePath)) {
|
|
_sink = File(_filePath!).openWrite(
|
|
mode: FileMode.writeOnlyAppend,
|
|
encoding: utf8,
|
|
);
|
|
} else {
|
|
_sink = null;
|
|
}
|
|
});
|
|
_timer = Timer.periodic(const Duration(seconds: 60 * 60 * 2),
|
|
(Timer timer) async {
|
|
final path = await AppFileTool.getLoggerBackupPath();
|
|
if (path == null) return;
|
|
unawaited(_enqueue(() async {
|
|
await _sink?.flush();
|
|
await _sink?.close();
|
|
_filePath = path;
|
|
_sink = File(_filePath!).openWrite(
|
|
mode: FileMode.writeOnlyAppend,
|
|
encoding: utf8,
|
|
);
|
|
}));
|
|
});
|
|
} catch (e, stack) {
|
|
print("初始化日志错误error:|$e|stack:|$stack|");
|
|
}
|
|
}
|
|
|
|
@override
|
|
Future<void> destroy() async {
|
|
_timer?.cancel();
|
|
_timer = null;
|
|
await _enqueue(() async {
|
|
await _sink?.flush();
|
|
await _sink?.close();
|
|
_sink = null;
|
|
});
|
|
}
|
|
|
|
@override
|
|
void output(OutputEvent event) {
|
|
try {
|
|
if (AppSysTool.isDev()) {
|
|
for (final v in event.lines) {
|
|
print(v);
|
|
}
|
|
}
|
|
unawaited(_enqueue(() async {
|
|
if (_filePath == null || _sink == null) return;
|
|
if (Level.debug == event.level) return;
|
|
_sink!.writeAll(event.lines, '\n');
|
|
_sink!.writeln();
|
|
await _sink!.flush();
|
|
}));
|
|
} catch (e, stack) {
|
|
print("写入日志错误error:|$e|stack:|$stack|");
|
|
}
|
|
}
|
|
}
|