logger.ha (1271B)
1 // SPDX-License-Identifier: MPL-2.0 2 // (c) Hare authors <https://harelang.org> 3 4 use fmt; 5 use io; 6 use os; 7 use time::date; 8 9 // Interface for implementing a logger. 10 export type logger = struct { 11 println: *fn(logger: *logger, fields: fmt::formattable...) void, 12 printfln: *fn(logger: *logger, fmt: str, fields: fmt::field...) void, 13 }; 14 15 export type stdlogger = struct { 16 logger, 17 sink: io::handle, 18 }; 19 20 // Creates a new standard logger. 21 export fn new(sink: io::handle) stdlogger = { 22 return stdlogger { 23 println = &log_println, 24 printfln = &log_printfln, 25 sink = sink, 26 }; 27 }; 28 29 fn log_println(sink: *logger, fields: fmt::formattable...) void = { 30 const sink = sink: *stdlogger; 31 assert(sink.println == &log_println); 32 const now = date::localnow(); 33 fmt::fprint(sink.sink, "["): void; 34 date::format(sink.sink, date::STAMP, &now): void; 35 fmt::fprint(sink.sink, "] "): void; 36 fmt::fprintln(sink.sink, fields...): void; 37 }; 38 39 fn log_printfln(sink: *logger, fmt: str, fields: fmt::field...) void = { 40 const sink = sink: *stdlogger; 41 assert(sink.printfln == &log_printfln); 42 const now = date::localnow(); 43 fmt::fprint(sink.sink, "["): void; 44 date::format(sink.sink, date::STAMP, &now): void; 45 fmt::fprint(sink.sink, "] "): void; 46 fmt::fprintfln(sink.sink, fmt, fields...): void; 47 };