wireguard-go/device/logger.go

69 lines
1.6 KiB
Go
Raw Normal View History

2019-01-02 00:55:51 +00:00
/* SPDX-License-Identifier: MIT
*
* Copyright (C) 2017-2020 WireGuard LLC. All Rights Reserved.
*/
2019-03-03 03:04:41 +00:00
package device
2017-06-27 15:33:06 +00:00
import (
"log"
"os"
)
// A Logger provides logging for a Device.
// The functions are Printf-style functions.
// They must be safe for concurrent use.
// They do not require a trailing newline in the format.
// If nil, that level of logging will be silent.
type Logger struct {
Debugf func(format string, args ...interface{})
Infof func(format string, args ...interface{})
Errorf func(format string, args ...interface{})
}
// Log levels for use with NewLogger.
2017-06-27 15:33:06 +00:00
const (
2018-05-14 01:38:06 +00:00
LogLevelSilent = iota
LogLevelError
2017-06-27 15:33:06 +00:00
LogLevelInfo
LogLevelDebug
)
// NewLogger constructs a Logger that writes to stdout.
// It logs at the specified log level and above.
// It decorates log lines with the log level, date, time, and prepend.
func NewLogger(level int, prepend string) *Logger {
2017-06-27 15:33:06 +00:00
logger := new(Logger)
logf := func(prefix string) func(string, ...interface{}) {
return log.New(os.Stdout, prefix+": "+prepend, log.Ldate|log.Ltime).Printf
}
if level >= LogLevelDebug {
logger.Debugf = logf("DEBUG")
}
if level >= LogLevelInfo {
logger.Infof = logf("INFO")
}
if level >= LogLevelError {
logger.Errorf = logf("ERROR")
}
2017-06-27 15:33:06 +00:00
return logger
}
func (device *Device) debugf(format string, args ...interface{}) {
if device.log.Debugf != nil {
device.log.Debugf(format, args...)
}
}
func (device *Device) infof(format string, args ...interface{}) {
if device.log.Infof != nil {
device.log.Infof(format, args...)
}
}
func (device *Device) errorf(format string, args ...interface{}) {
if device.log.Errorf != nil {
device.log.Errorf(format, args...)
}
}