add SetLogLevelByName

This commit is contained in:
bryanqiu 2023-07-21 11:24:30 +08:00
parent e27ea9f370
commit 6126b66f6a

56
log.go
View File

@ -16,16 +16,38 @@ import (
) )
const ( const (
PANIC logLevel = 0 PANIC LogLevel = 0
FATAL logLevel = 1 FATAL LogLevel = 1
ERROR logLevel = 2 ERROR LogLevel = 2
NOTICE logLevel = 3 NOTICE LogLevel = 3
WARNING logLevel = 4 WARNING LogLevel = 4
INFO logLevel = 5 INFO LogLevel = 5
DEBUG logLevel = 9 DEBUG LogLevel = 9
ErrLogLevel = "~~~~~invalid loglevel~~~~~"
ErrLogPanic = "~~~~panic~~~~~~" ErrLogPanic = "~~~~panic~~~~~~"
) )
var (
mapStrToLevel = map[string]LogLevel{
"PANIC": PANIC,
"FATAL": FATAL,
"ERROR": ERROR,
"NOTICE": NOTICE,
"WARNING": WARNING,
"INFO": INFO,
"DEBUG": DEBUG,
}
mapLevelToStr = map[LogLevel]string{
PANIC: "PANIC",
FATAL: "FATAL",
ERROR: "ERROR",
NOTICE: "NOTICE",
WARNING: "WARNING",
INFO: "INFO",
DEBUG: "DEBUG",
}
)
var ( var (
golog *log.Logger = nil golog *log.Logger = nil
mylog *Logger = nil mylog *Logger = nil
@ -33,11 +55,11 @@ var (
modulelogs map[string]*Logger = map[string]*Logger{} modulelogs map[string]*Logger = map[string]*Logger{}
) )
type logLevel int type LogLevel int
type Logger struct { type Logger struct {
module string module string
golog *log.Logger golog *log.Logger
loglevel logLevel loglevel LogLevel
} }
type LogidCreator interface { type LogidCreator interface {
@ -62,13 +84,23 @@ func New(module string) *Logger {
} }
} }
// //////////////////////////////////////////////////////////////// // SetLogLevel set new log level
func (log *Logger) SetLogLevel(newlv logLevel) (oldlv logLevel) { func (log *Logger) SetLogLevel(newlv LogLevel) (oldlv LogLevel) {
oldlv = log.loglevel oldlv = log.loglevel
log.loglevel = newlv log.loglevel = newlv
return oldlv return oldlv
} }
// SetLogLevelByName set new log level by level name
func (log *Logger) SetLogLevelByName(newlv string) (oldlv string) {
if newlevel, ok := mapStrToLevel[newlv]; ok {
oldlv = log.loglevel
log.loglevel = newlevel
return mapLevelToStr[oldlv]
}
return ErrLogLevel
}
func (log *Logger) Print(prefix string, v interface{}) { func (log *Logger) Print(prefix string, v interface{}) {
var str = "" var str = ""
if pkg, err := json.Marshal(v); err != nil { if pkg, err := json.Marshal(v); err != nil {
@ -134,7 +166,7 @@ func (log *Logger) GetLogidStr(format string) string {
return "" return ""
} }
func (log *Logger) logwrite(typ logLevel, calldepth int, format string, v ...interface{}) { func (log *Logger) logwrite(typ LogLevel, calldepth int, format string, v ...interface{}) {
if typ > log.loglevel { if typ > log.loglevel {
return return
} }