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
import (
"fmt"
)
// Level ...
type Level int
@ -31,19 +35,41 @@ const (
FatalLevel
)
func (l Level) string() string {
func (l Level) string() (lvl string) {
switch l {
case DebugLevel:
return "DEBUG"
lvl = "DEBUG"
case InfoLevel:
return "INFO"
lvl = "INFO"
case WarningLevel:
return "WARNING"
lvl = "WARNING"
case ErrorLevel:
return "ERROR"
lvl = "ERROR"
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"
)
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.
type Logger struct {

View File

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