[feat] package nazalog: 1. new func Sync() 2. auto sync while panic or fatal

pull/2/head
q191201771 5 years ago
parent 0cb50aed18
commit 607fc70f30

@ -94,6 +94,10 @@ func Out(level Level, calldepth int, s string) {
global.Out(level, calldepth, s)
}
func Sync() {
global.Sync()
}
// 这里不加锁保护如果要调用Init函数初始化全局的Logger那么由调用方保证调用Init函数时不会并发调用全局Logger的其他方法
func Init(modOptions ...ModOption) error {
var err error

@ -45,6 +45,8 @@ type Logger interface {
Outputf(level Level, calldepth int, format string, v ...interface{})
Output(level Level, calldepth int, v ...interface{})
Out(level Level, calldepth int, s string)
Sync()
}
type Option struct {

@ -11,7 +11,6 @@ package nazalog
import (
"bytes"
"fmt"
"io"
"os"
"runtime"
"sync"
@ -62,7 +61,7 @@ type logger struct {
m sync.Mutex
fp *os.File
console io.Writer
console *os.File
buf bytes.Buffer
currRoundTime time.Time
}
@ -170,6 +169,9 @@ func (l *logger) Out(level Level, calldepth int, s string) {
// 输出至控制台
if l.console != nil {
_, _ = l.console.Write(l.buf.Bytes())
if level == LevelFatal || level == LevelPanic {
_ = l.console.Sync()
}
}
// 输出至日志文件
@ -183,6 +185,21 @@ func (l *logger) Out(level Level, calldepth int, s string) {
l.currRoundTime = now
}
_, _ = l.fp.Write(l.buf.Bytes())
if level == LevelFatal || level == LevelPanic {
_ = l.fp.Sync()
}
}
}
func (l *logger) Sync() {
l.m.Lock()
defer l.m.Unlock()
if l.console != nil {
_ = l.console.Sync()
}
if l.fp != nil {
_ = l.fp.Sync()
}
}

@ -73,6 +73,7 @@ func TestGlobal(t *testing.T) {
Outputf(LevelInfo, 3, "gc test msg by Output%s", "f")
Output(LevelInfo, 3, "gc test msg by Output")
Out(LevelInfo, 3, "gc test msg by Out")
Sync()
}
func TestNew(t *testing.T) {

Loading…
Cancel
Save