File: logger.go

package info (click to toggle)
golang-github-coredhcp-coredhcp 0.0.0%2Bgit.20250806.f7e98e4-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 460 kB
  • sloc: makefile: 8; sh: 6
file content (46 lines) | stat: -rw-r--r-- 1,156 bytes parent folder | download
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
// Copyright 2018-present the CoreDHCP Authors. All rights reserved
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.

package logger

import (
	"io"
	"sync"

	log_prefixed "github.com/chappjc/logrus-prefix"
	"github.com/rifflock/lfshook"
	"github.com/sirupsen/logrus"
)

var (
	globalLogger   *logrus.Logger
	getLoggerMutex sync.Mutex
)

// GetLogger returns a configured logger instance
func GetLogger(prefix string) *logrus.Entry {
	if prefix == "" {
		prefix = "<no prefix>"
	}
	if globalLogger == nil {
		getLoggerMutex.Lock()
		defer getLoggerMutex.Unlock()
		logger := logrus.New()
		logger.SetFormatter(&log_prefixed.TextFormatter{
			FullTimestamp: true,
		})
		globalLogger = logger
	}
	return globalLogger.WithField("prefix", prefix)
}

// WithFile logs to the specified file in addition to the existing output.
func WithFile(log *logrus.Entry, logfile string) {
	log.Logger.AddHook(lfshook.NewHook(logfile, &logrus.TextFormatter{}))
}

// WithNoStdOutErr disables logging to stdout/stderr.
func WithNoStdOutErr(log *logrus.Entry) {
	log.Logger.SetOutput(io.Discard)
}