v2ray-core/common/log/log.go

115 lines
2.2 KiB
Go
Raw Normal View History

package log
import (
"fmt"
2016-01-18 11:24:33 +00:00
"github.com/v2ray/v2ray-core/common/serial"
)
const (
DebugLevel = LogLevel(0)
InfoLevel = LogLevel(1)
WarningLevel = LogLevel(2)
ErrorLevel = LogLevel(3)
)
2015-12-05 20:10:14 +00:00
type errorLog struct {
prefix string
values []interface{}
}
2015-12-05 20:10:14 +00:00
func (this *errorLog) String() string {
2016-01-18 11:24:33 +00:00
data := ""
for _, value := range this.values {
switch typedVal := value.(type) {
case string:
data += typedVal
case *string:
data += *typedVal
case serial.String:
data += typedVal.String()
case error:
data += typedVal.Error()
default:
data += fmt.Sprintf("%v", value)
}
2015-09-12 18:36:21 +00:00
}
2015-12-05 20:10:14 +00:00
return this.prefix + data
}
var (
2015-12-05 20:10:14 +00:00
noOpLoggerInstance logWriter = &noOpLogWriter{}
streamLoggerInstance logWriter = newStdOutLogWriter()
debugLogger = noOpLoggerInstance
infoLogger = noOpLoggerInstance
2015-12-02 23:41:34 +00:00
warningLogger = streamLoggerInstance
errorLogger = streamLoggerInstance
)
type LogLevel int
func SetLogLevel(level LogLevel) {
debugLogger = noOpLoggerInstance
if level <= DebugLevel {
debugLogger = streamLoggerInstance
}
infoLogger = noOpLoggerInstance
if level <= InfoLevel {
infoLogger = streamLoggerInstance
}
warningLogger = noOpLoggerInstance
if level <= WarningLevel {
warningLogger = streamLoggerInstance
}
errorLogger = noOpLoggerInstance
if level <= ErrorLevel {
errorLogger = streamLoggerInstance
}
}
2015-12-05 20:10:14 +00:00
func InitErrorLogger(file string) error {
logger, err := newFileLogWriter(file)
if err != nil {
2016-01-18 11:24:33 +00:00
Error("Failed to create error logger on file (", file, "): ", err)
2015-12-05 20:10:14 +00:00
return err
}
streamLoggerInstance = logger
return nil
}
2015-10-15 11:15:59 +00:00
// Debug outputs a debug log with given format and optional arguments.
2016-01-18 11:24:33 +00:00
func Debug(v ...interface{}) {
2015-12-05 20:10:14 +00:00
debugLogger.Log(&errorLog{
prefix: "[Debug]",
values: v,
})
2015-09-12 09:51:42 +00:00
}
2015-10-15 11:15:59 +00:00
// Info outputs an info log with given format and optional arguments.
2016-01-18 11:24:33 +00:00
func Info(v ...interface{}) {
2015-12-05 20:10:14 +00:00
infoLogger.Log(&errorLog{
prefix: "[Info]",
values: v,
})
}
2015-10-15 11:15:59 +00:00
// Warning outputs a warning log with given format and optional arguments.
2016-01-18 11:24:33 +00:00
func Warning(v ...interface{}) {
2015-12-05 20:10:14 +00:00
warningLogger.Log(&errorLog{
prefix: "[Warning]",
values: v,
})
}
2015-10-15 11:15:59 +00:00
// Error outputs an error log with given format and optional arguments.
2016-01-18 11:24:33 +00:00
func Error(v ...interface{}) {
2015-12-05 20:10:14 +00:00
errorLogger.Log(&errorLog{
prefix: "[Error]",
values: v,
})
}