1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

log: allow file logging

This commit is contained in:
yep84 2019-07-24 17:50:29 +02:00 committed by Alexander Medvednikov
parent 049d78a78d
commit 94a599d630
2 changed files with 51 additions and 10 deletions

View File

@ -1,7 +1,7 @@
import log import log
fn main(){ fn main(){
mut l := log.Log{level:log.INFO} mut l := log.Log{level:log.INFO, 'terminal'}
l.info('info') l.info('info')
l.warn('warn') l.warn('warn')
l.error('error') l.error('error')

View File

@ -1,5 +1,7 @@
module log module log
import os
import time
import term import term
const ( const (
@ -13,6 +15,7 @@ const (
struct Log{ struct Log{
mut: mut:
level int level int
output string
} }
@ -20,34 +23,72 @@ pub fn (l mut Log) set_level(level int){
l.level = level 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){ pub fn (l Log) fatal(s string){
panic(s) panic(s)
} }
pub fn (l Log) error(s string){ pub fn (l Log) error(s string){
if l.level >= ERROR{ if l.level >= ERROR{
f := term.red('E') switch l.output {
println('[$f]$s') case 'terminal':
f := term.red('E')
println('[$f]$s')
default:
l.log_file(s, 'E')
}
} }
} }
pub fn (l Log) warn(s string){ pub fn (l Log) warn(s string){
if l.level >= WARN{ if l.level >= WARN{
f := term.yellow('W') switch l.output {
println('[$f]$s') case 'terminal':
f := term.yellow('W')
println('[$f]$s')
default:
l.log_file(s, 'W')
}
} }
} }
pub fn (l Log) info(s string){ pub fn (l Log) info(s string){
if l.level >= INFO{ if l.level >= INFO{
f := term.white('I') switch l.output {
println('[$f]$s') case 'terminal':
f := term.white('I')
println('[$f]$s')
default:
l.log_file(s, 'I')
}
} }
} }
pub fn (l Log) debug(s string){ pub fn (l Log) debug(s string){
if l.level >= DEBUG{ if l.level >= DEBUG{
f := term.blue('D') switch l.output {
println('[$f]$s') case 'terminal':
f := term.blue('D')
println('[$f]$s')
default:
l.log_file(s, 'D')
}
} }
} }