From 20fd1445a085ab4c5781f93677f46fb8f6985028 Mon Sep 17 00:00:00 2001 From: q191201771 <191201771@qq.com> Date: Wed, 4 Sep 2019 15:47:07 +0800 Subject: [PATCH] =?UTF-8?q?package=20log:=20=E5=A2=9E=E5=8A=A0=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=20FatalIfErrorNotNil?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/log/log.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/pkg/log/log.go b/pkg/log/log.go index daff98b..6318745 100644 --- a/pkg/log/log.go +++ b/pkg/log/log.go @@ -28,6 +28,9 @@ type Logger interface { Warn(v ...interface{}) Error(v ...interface{}) + // 打印错误并退出程序,日志级别为 LevelError + FatalIfErrorNotNil(err error) + Outputf(level Level, calldepth int, format string, v ...interface{}) Output(level Level, calldepth int, v ...interface{}) } @@ -157,6 +160,13 @@ func (l *logger) Error(v ...interface{}) { l.Output(LevelError, 3, v...) } +func (l *logger) FatalIfErrorNotNil(err error) { + if err != nil { + l.Outputf(LevelError, 3, "fatal since error not nil. err=%+v", err) + os.Exit(1) + } +} + // TODO chef: Outputf 和 Output 代码重复 func (l *logger) Outputf(level Level, calldepth int, format string, v ...interface{}) { if l.c.Level > level { @@ -252,6 +262,13 @@ func Error(v ...interface{}) { global.Output(LevelError, 3, v...) } +func FatalIfErrorNotNil(err error) { + if err != nil { + global.Outputf(LevelError, 3, "fatal since error not nil. err=%+v", err) + os.Exit(1) + } +} + func Outputf(level Level, calldepth int, format string, v ...interface{}) { global.Outputf(level, calldepth, format, v...) }