// Copyright (C) 2025, uvok cheetah
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see .
import 'package:logger/logger.dart';
Logger fileLogger([String? name]) {
String fileName = "???";
if (name == null) {
final String? callerName = StackTrace.current
.toString()
.split('\n')
.elementAtOrNull(1);
if (callerName != null) {
final int start = callerName.indexOf("package:");
if (start != -1) {
final int fileNameStart = start + "package:".length;
final int end = callerName.indexOf(":", fileNameStart);
if (end != -1 && end > fileNameStart) {
fileName = callerName.substring(fileNameStart, end);
}
}
}
} else {
fileName = name;
}
return Logger(printer: FilePrefixPrinter(SimplePrinter(), fileName));
}
class FilePrefixPrinter extends LogPrinter {
final LogPrinter delegate;
final String fileName;
FilePrefixPrinter(this.delegate, this.fileName);
@override
List log(LogEvent event) {
final lines = delegate.log(event);
return lines.map((line) {
// ugh..... relying on implementation details...
var e = line.indexOf("[0m") + 3;
return '${line.substring(0, e)} [$fileName] ${line.substring(e)}';
}).toList();
}
}