v/vlib/log/log.v

140 lines
2.2 KiB
V
Raw Normal View History

2019-06-26 02:14:38 +02:00
module log
2019-07-24 17:50:29 +02:00
import os
import time
2019-07-01 17:09:22 +02:00
import term
2019-06-26 02:14:38 +02:00
2019-11-25 05:50:59 +01:00
pub enum LogLevel {
fatal
error
warning
info
debug
}
fn tag(l LogLevel) string {
return match l {
.fatal { term.red('F') }
.error { term.red('E') }
.warning { term.yellow('W') }
.info { term.white('I') }
.debug { term.blue('D') }
else { ' ' }
}
}
2019-10-28 16:53:02 +01:00
pub const (
2019-11-25 05:50:59 +01:00
FATAL = 1
ERROR = 2
WARN = 3
INFO = 4
DEBUG = 5
2019-06-26 02:14:38 +02:00
)
interface Logger {
2019-11-25 05:50:59 +01:00
fatal(s string)
error(s string)
warn(s string)
info(s string)
debug(s string)
}
2019-10-28 16:53:02 +01:00
pub struct Log {
2019-11-25 05:50:59 +01:00
mut:
level LogLevel
output_label string
output_to_file bool
2019-06-26 02:14:38 +02:00
}
pub fn (l mut Log) set_level(level int){
2019-11-25 05:50:59 +01:00
l.level = match level {
FATAL { LogLevel.fatal }
ERROR { LogLevel.error }
WARN { LogLevel.warning }
INFO { LogLevel.info }
DEBUG { LogLevel.debug }
else { .debug }
}
}
pub fn (l mut Log) set_output_level(level LogLevel){
l.level = level
2019-06-26 02:14:38 +02:00
}
2019-11-25 05:50:59 +01:00
pub fn (l mut Log) set_output_label(label string) {
l.output_label = label
2019-07-24 17:50:29 +02:00
}
2019-11-25 05:50:59 +01:00
pub fn (l mut Log) set_output(output string){
l.output_label = output
}
fn (l Log) log_file(s string, level LogLevel) {
filename := '${l.output_label}.log'.replace(' ', '')
f := os.open_append(filename) or {
panic('error reading file $filename')
}
timestamp := time.now().format_ss()
e := tag(level)
f.writeln('$timestamp [$e] $s')
}
fn (l Log) log_cli(s string, level LogLevel) {
f := tag(level)
t := time.now()
println('[$f ${t.format_ss()}] $s')
2019-07-24 17:50:29 +02:00
}
2019-06-26 02:14:38 +02:00
pub fn (l Log) fatal(s string){
2019-11-25 05:50:59 +01:00
if l.level == .fatal {
if l.output_to_file {
l.log_file(s, .fatal)
} else {
l.log_cli(s, .fatal)
}
panic('$l.output_label: $s')
}
2019-06-26 02:14:38 +02:00
}
pub fn (l Log) error(s string){
2019-11-25 05:50:59 +01:00
if l.level in [.info, .debug, .warning, .error] {
if l.output_to_file {
l.log_file(s, .error)
} else {
l.log_cli(s, .error)
}
}
2019-06-26 02:14:38 +02:00
}
pub fn (l Log) warn(s string){
2019-11-25 05:50:59 +01:00
if l.level in [.info, .debug, .warning] {
if l.output_to_file {
l.log_file(s, .warning)
} else {
l.log_cli(s, .warning)
}
}
2019-06-26 02:14:38 +02:00
}
pub fn (l Log) info(s string){
2019-11-25 05:50:59 +01:00
if l.level in [.info, .debug] {
if l.output_to_file {
l.log_file(s, .info)
} else {
l.log_cli(s, .info)
}
}
2019-06-26 02:14:38 +02:00
}
pub fn (l Log) debug(s string){
2019-11-25 05:50:59 +01:00
if l.level != .debug {
return
}
if l.output_to_file {
l.log_file(s, .debug)
} else {
l.log_cli(s, .debug)
}
2019-07-16 17:59:07 +02:00
}