From 13645e24569811a61a49d1e85d76e24f653eac42 Mon Sep 17 00:00:00 2001 From: kbkpbot Date: Sun, 20 Apr 2025 08:25:13 +0800 Subject: [PATCH] log: add local time / utc time selection support (#24268) --- vlib/log/log.v | 15 +++++++++++++-- vlib/log/log_test.v | 7 +++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/vlib/log/log.v b/vlib/log/log.v index 410fe372fe..42f43fb0b3 100644 --- a/vlib/log/log.v +++ b/vlib/log/log.v @@ -38,6 +38,7 @@ mut: time_format TimeFormat = .tf_rfc3339_micro custom_time_format string = 'MMMM Do YY N kk:mm:ss A' // timestamp with custom format short_tag bool + local_time bool // use local time or utc time in log always_flush bool // flush after every single .fatal(), .error(), .warn(), .info(), .debug() call output_stream io.Writer = stderr pub mut: @@ -119,7 +120,7 @@ pub fn (mut l Log) reopen() ! { // log_file writes log line `s` with `level` to the log file. fn (mut l Log) log_file(s string, level Level) { - timestamp := l.time_format(time.utc()) + timestamp := l.time_format(if l.local_time { time.now() } else { time.utc() }) e := tag_to_file(level, l.short_tag) unsafe { @@ -142,7 +143,7 @@ fn (mut l Log) log_file(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()) + timestamp := l.time_format(if l.local_time { time.now() } else { time.utc() }) tag := tag_to_console(level, l.short_tag) msg := '${timestamp} [${tag}] ${s}\n' arr := msg.bytes() @@ -313,6 +314,16 @@ pub fn (l Log) get_short_tag() bool { return l.short_tag } +// set_local_time will set the log using local time +pub fn (mut l Log) set_local_time(enabled bool) { + l.local_time = enabled +} + +// get_local_time will get the log using local time state +pub fn (l Log) get_local_time() bool { + return l.local_time +} + // use_stdout will restore the old behaviour of logging to stdout, instead of stderr. // It will also silence the deprecation note in the transition period. pub fn use_stdout() { diff --git a/vlib/log/log_test.v b/vlib/log/log_test.v index 7195191009..90d5f94957 100644 --- a/vlib/log/log_test.v +++ b/vlib/log/log_test.v @@ -134,6 +134,13 @@ fn test_log_time_format() { assert TimeFormat.tf_custom_format == l.get_time_format() l.info('${@FN} custom like January 1st 22 AD 13:45:33 PM') assert true + l.set_time_format(.tf_default) + l.set_local_time(true) + l.info('${@FN} time log in local time') + assert l.get_local_time() + l.set_local_time(false) + l.info('${@FN} time log in utc time') + assert !l.get_local_time() println(@FN + ' end') }