From d49bf35757d3d77c4ef66635de00c8b6e3fc64b8 Mon Sep 17 00:00:00 2001 From: uvok Date: Sun, 3 Aug 2025 18:07:13 +0200 Subject: Use file prefix logger --- lib/log.dart | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 lib/log.dart (limited to 'lib/log.dart') diff --git a/lib/log.dart b/lib/log.dart new file mode 100644 index 0000000..6029ae9 --- /dev/null +++ b/lib/log.dart @@ -0,0 +1,58 @@ +// 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(); + } +} -- cgit v1.2.3