84 lines
2.0 KiB
Dart
84 lines
2.0 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(
|
|
printer: customPrinter,
|
|
output: ConsoleOutput(),
|
|
);
|
|
final customPrinter = PrettyPrinter(
|
|
lineLength: 0,
|
|
methodCount: 1,
|
|
errorMethodCount: 1,
|
|
colors: true,
|
|
printEmojis: false,
|
|
printTime: true,
|
|
);
|
|
|
|
class ConsoleOutput extends LogOutput {
|
|
String? _filePath;
|
|
IOSink? _sink;
|
|
Timer? _timer;
|
|
|
|
@override
|
|
Future<void> init() async {
|
|
try {
|
|
// 关闭旧的sink并创建新的
|
|
await _sink?.flush();
|
|
await _sink?.close();
|
|
_filePath = await AppFileTool.getLoggerBackupPath();
|
|
if (ObjectUtil.isNotEmpty(_filePath)) {
|
|
_sink = File(_filePath!).openWrite(
|
|
mode: FileMode.writeOnlyAppend,
|
|
encoding: utf8,
|
|
);
|
|
}
|
|
_timer = Timer.periodic(const Duration(seconds: 60 * 60 * 2),
|
|
(Timer timer) async {
|
|
final path = await AppFileTool.getLoggerBackupPath();
|
|
if (path == null) return;
|
|
// 关闭旧的sink并创建新的
|
|
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 {
|
|
await _sink?.flush();
|
|
await _sink?.close();
|
|
_timer?.cancel();
|
|
}
|
|
|
|
@override
|
|
void output(OutputEvent event) {
|
|
try {
|
|
if (AppSysTool.isDev()) {
|
|
for (final v in event.lines) {
|
|
print(v);
|
|
}
|
|
} else {
|
|
if (_filePath == null) return;
|
|
if (_sink == null) return;
|
|
if (Level.debug == event.level) return;
|
|
_sink?.writeAll(event.lines, '\n');
|
|
}
|
|
} catch (e, stack) {
|
|
print("写入日志错误error:|$e|stack:|$stack|");
|
|
}
|
|
}
|
|
}
|