log: set stderr as default log output, add .set_output_stream() (#23296)

This commit is contained in:
gechandesu 2024-12-28 22:54:06 +03:00 committed by GitHub
parent 84baf4d9e5
commit a47b7298c4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 40 additions and 35 deletions

View file

@ -19,8 +19,8 @@ pub enum LogTarget {
both
}
// tag_to_cli returns the tag for log level `l` as a colored string.
fn tag_to_cli(l Level, short_tag bool) string {
// tag_to_console returns the tag for log level `l` as a colored string.
fn tag_to_console(l Level, short_tag bool) string {
if short_tag {
return match l {
.disabled { ' ' }

View file

@ -5,6 +5,7 @@ module log
import os
import time
import io
// TimeFormat define the log time string format, come from time/format.v
pub enum TimeFormat {
@ -36,6 +37,7 @@ mut:
custom_time_format string = 'MMMM Do YY N kk:mm:ss A' // timestamp with custom format
short_tag bool
always_flush bool // flush after every single .fatal(), .error(), .warn(), .info(), .debug() call
output_stream io.Writer = os.stderr()
pub mut:
output_file_name string // log output to this file
}
@ -77,6 +79,11 @@ pub fn (mut l Log) set_output_path(output_file_path string) {
l.ofile = ofile
}
// set_output_stream sets the output stream to write log e.g. stderr, stdout, etc.
pub fn (mut l Log) set_output_stream(stream io.Writer) {
l.output_stream = stream
}
// log_to_console_too turns on logging to the console too, in addition to logging to a file.
// You have to call it *after* calling .set_output_path(output_file_path).
pub fn (mut l Log) log_to_console_too() {
@ -131,13 +138,19 @@ fn (mut l Log) log_file(s string, level Level) {
}
}
// log_cli writes log line `s` with `level` to stdout.
fn (l &Log) log_cli(s string, level Level) {
// log_stream writes log line `s` with `level` to stderr or stderr depending on set output stream.
fn (mut l Log) log_stream(s string, level Level) {
timestamp := l.time_format(time.utc())
e := tag_to_cli(level, l.short_tag)
println('${timestamp} [${e}] ${s}')
tag := tag_to_console(level, l.short_tag)
msg := '${timestamp} [${tag}] ${s}\n'
arr := msg.bytes()
l.output_stream.write(arr) or {}
if l.always_flush {
flush_stdout()
match (l.output_stream as os.File).fd {
1 { flush_stdout() }
2 { flush_stderr() }
else {}
}
}
}
@ -148,7 +161,7 @@ pub fn (mut l Log) send_output(s &string, level Level) {
l.log_file(s, level)
}
if l.output_target == .console || l.output_target == .both {
l.log_cli(s, level)
l.log_stream(s, level)
}
}
@ -202,6 +215,7 @@ pub fn (mut f Log) free() {
f.output_label.free()
f.ofile.close()
f.output_file_name.free()
f.output_stream.free()
}
}