From 94a599d630e036bb8eaa236d9b6631a9d6cdee2e Mon Sep 17 00:00:00 2001 From: yep84 <52426534+yep84@users.noreply.github.com> Date: Wed, 24 Jul 2019 17:50:29 +0200 Subject: [PATCH] log: allow file logging --- examples/log.v | 2 +- vlib/log/log.v | 59 ++++++++++++++++++++++++++++++++++++++++++-------- 2 files changed, 51 insertions(+), 10 deletions(-) diff --git a/examples/log.v b/examples/log.v index e49b251021..d60fb53bf5 100644 --- a/examples/log.v +++ b/examples/log.v @@ -1,7 +1,7 @@ import log fn main(){ - mut l := log.Log{level:log.INFO} + mut l := log.Log{level:log.INFO, 'terminal'} l.info('info') l.warn('warn') l.error('error') diff --git a/vlib/log/log.v b/vlib/log/log.v index a61595e51b..8e64724f61 100644 --- a/vlib/log/log.v +++ b/vlib/log/log.v @@ -1,5 +1,7 @@ module log +import os +import time import term const ( @@ -13,6 +15,7 @@ const ( struct Log{ mut: level int + output string } @@ -20,34 +23,72 @@ pub fn (l mut Log) set_level(level int){ l.level = level } +pub fn (l mut Log) set_output(output string) { + l.output = output +} + +fn (l Log) log_file(s string, e string) { + filename := l.output + f := os.open_append(l.output) or { + panic('error reading file $filename') + return + } + timestamp := time.now().format_ss() + f.writeln('$timestamp [$e] $s') +} + pub fn (l Log) fatal(s string){ panic(s) } pub fn (l Log) error(s string){ if l.level >= ERROR{ - f := term.red('E') - println('[$f]$s') + switch l.output { + case 'terminal': + f := term.red('E') + println('[$f]$s') + + default: + l.log_file(s, 'E') + } } } pub fn (l Log) warn(s string){ if l.level >= WARN{ - f := term.yellow('W') - println('[$f]$s') - } + switch l.output { + case 'terminal': + f := term.yellow('W') + println('[$f]$s') + + default: + l.log_file(s, 'W') + } + } } pub fn (l Log) info(s string){ if l.level >= INFO{ - f := term.white('I') - println('[$f]$s') + switch l.output { + case 'terminal': + f := term.white('I') + println('[$f]$s') + + default: + l.log_file(s, 'I') + } } } pub fn (l Log) debug(s string){ if l.level >= DEBUG{ - f := term.blue('D') - println('[$f]$s') + switch l.output { + case 'terminal': + f := term.blue('D') + println('[$f]$s') + + default: + l.log_file(s, 'D') + } } }