initialize log level when import log package

This commit is contained in:
Wenkai Yin 2016-03-16 15:54:59 +08:00
parent bd0617b2a3
commit 0471e6ca3d
3 changed files with 61 additions and 15 deletions

View File

@ -15,6 +15,10 @@
package log package log
import (
"fmt"
)
// Level ... // Level ...
type Level int type Level int
@ -31,19 +35,41 @@ const (
FatalLevel FatalLevel
) )
func (l Level) string() string { func (l Level) string() (lvl string) {
switch l { switch l {
case DebugLevel: case DebugLevel:
return "DEBUG" lvl = "DEBUG"
case InfoLevel: case InfoLevel:
return "INFO" lvl = "INFO"
case WarningLevel: case WarningLevel:
return "WARNING" lvl = "WARNING"
case ErrorLevel: case ErrorLevel:
return "ERROR" lvl = "ERROR"
case FatalLevel: case FatalLevel:
return "FATAL" lvl = "FATAL"
default:
lvl = "UNKNOWN"
} }
return "unknown" return
}
func parseLevel(lvl string) (level Level, err error) {
switch lvl {
case "debug":
level = DebugLevel
case "info":
level = InfoLevel
case "warning":
level = WarningLevel
case "error":
level = ErrorLevel
case "fatal":
level = FatalLevel
default:
err = fmt.Errorf("invalid log level: %s", lvl)
}
return
} }

View File

@ -24,7 +24,25 @@ import (
"time" "time"
) )
var logger = New(os.Stdout, NewTextFormatter(""), WarningLevel) var logger = New(os.Stdout, NewTextFormatter(), WarningLevel)
func init() {
// TODO add item in configuaration file
lvl := os.Getenv("LOG_LEVEL")
if len(lvl) == 0 {
logger.SetLevel(InfoLevel)
return
}
level, err := parseLevel(lvl)
if err != nil {
logger.SetLevel(InfoLevel)
return
}
logger.SetLevel(level)
}
// Logger provides a struct with fields that describe the details of logger. // Logger provides a struct with fields that describe the details of logger.
type Logger struct { type Logger struct {

View File

@ -27,14 +27,10 @@ type TextFormatter struct {
timeFormat string timeFormat string
} }
// NewTextFormatter returns a customized TextFormatter // NewTextFormatter returns a TextFormatter, the format of time is time.RFC3339
func NewTextFormatter(timeFormat string) *TextFormatter { func NewTextFormatter() *TextFormatter {
if len(timeFormat) == 0 {
timeFormat = defaultTimeFormat
}
return &TextFormatter{ return &TextFormatter{
timeFormat: timeFormat, timeFormat: defaultTimeFormat,
} }
} }
@ -58,3 +54,9 @@ func (t *TextFormatter) Format(r *Record) (b []byte, err error) {
return return
} }
func (t *TextFormatter) SetTimeFormat(fmt string) {
if len(fmt) != 0 {
t.timeFormat = fmt
}
}