JJ_MKVMaker/lib/app/controller/app_log.dart

32 lines
1.2 KiB
Dart

import 'dart:io';
/// 작업 기록. 약속: [add] 는 "[시:분:초] 글" 을 [lines] 에 (최근 500줄) 남기고, [file] 이 있으면 날짜와 함께 파일에도 쓴다.
/// 파일은 2MB 를 넘으면 "이름.1" 로 옮기고 새로 시작한다 (프로그램이 갑자기 꺼져도 무슨 일이 있었는지 볼 수 있게).
/// 파일에 쓰지 못해도 기록은 남는다.
class AppLog {
final List<String> lines = [];
/// 작업 기록을 파일에도 남길 곳 (설정 폴더의 app.log)
String? file;
static const maxLines = 500, maxFileBytes = 2 * 1024 * 1024;
void add(String msg, {DateTime? at}) {
final t = at ?? DateTime.now();
String two(int n) => n.toString().padLeft(2, '0');
lines.add('[${two(t.hour)}:${two(t.minute)}:${two(t.second)}] $msg');
if (lines.length > maxLines) lines.removeAt(0);
_append('${t.year}-${two(t.month)}-${two(t.day)} ${two(t.hour)}:${two(t.minute)}:${two(t.second)} $msg');
}
void _append(String line) {
final path = file;
if (path == null) return;
try {
final f = File(path);
if (f.existsSync() && f.lengthSync() > maxFileBytes) f.renameSync('$path.1');
f.writeAsStringSync('$line\n', mode: FileMode.append, flush: true);
} catch (_) {}
}
}