aboutsummaryrefslogtreecommitdiff
path: root/device/logger.go
blob: 6869a2433970604474159a801eef3088c95f3fdc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/* SPDX-License-Identifier: MIT
 *
 * Copyright (C) 2017-2020 WireGuard LLC. All Rights Reserved.
 */

package device

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.
const (
	LogLevelSilent = iota
	LogLevelError
	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 {
	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")
	}
	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...)
	}
}