Skip to content

Commit

Permalink
chore(logging): Refactor code (#15556)
Browse files Browse the repository at this point in the history
  • Loading branch information
srebhan authored Jun 25, 2024
1 parent 6da035b commit 32a5b44
Show file tree
Hide file tree
Showing 15 changed files with 351 additions and 270 deletions.
2 changes: 1 addition & 1 deletion cmd/telegraf/cmd_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ To migrate the file 'mysettings.conf' use
},
Action: func(cCtx *cli.Context) error {
// Setup logging
logConfig := logger.Config{Debug: cCtx.Bool("debug")}
logConfig := &logger.Config{Debug: cCtx.Bool("debug")}
if err := logger.SetupLogging(logConfig); err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/telegraf/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ func runApp(args []string, outputBuffer io.Writer, pprof Server, c TelegrafConfi
return fmt.Errorf("unknown command %q", cCtx.Args().First())
}

err := logger.SetupLogging(logger.Config{})
err := logger.SetupLogging(&logger.Config{})
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/telegraf/telegraf.go
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,7 @@ func (t *Telegraf) runAgent(ctx context.Context, reloadConfig bool) error {
}

// Setup logging as configured.
logConfig := logger.Config{
logConfig := &logger.Config{
Debug: c.Agent.Debug || t.debug,
Quiet: c.Agent.Quiet || t.quiet,
LogTarget: c.Agent.LogTarget,
Expand Down
7 changes: 0 additions & 7 deletions cmd/telegraf/telegraf_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ import (
"golang.org/x/sys/windows/svc"
"golang.org/x/sys/windows/svc/eventlog"
"golang.org/x/sys/windows/svc/mgr"

"github.com/influxdata/telegraf/logger"
)

func getLockedMemoryLimit() uint64 {
Expand All @@ -31,11 +29,6 @@ func getLockedMemoryLimit() uint64 {
}

func (t *Telegraf) Run() error {
// Register the eventlog logging target for windows.
if err := logger.RegisterEventLogger(t.serviceName); err != nil {
return err
}

// Process the service commands
if t.service != "" {
fmt.Println("The use of --service is deprecated, please use the 'service' command instead!")
Expand Down
1 change: 0 additions & 1 deletion config/deprecation.go
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,6 @@ func printPluginDeprecationNotice(level telegraf.LogLevel, name string, info tel
switch level {
case telegraf.Warn, telegraf.Error:
prefix := deprecationPrefix(level)

log.Printf(
"%s: Plugin %q deprecated since version %s and will be removed in %s: %s",
prefix, name, info.Since, info.RemovalIn, info.Notice,
Expand Down
12 changes: 1 addition & 11 deletions config/deprecation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,6 @@ func TestPluginDeprecation(t *testing.T) {
}

if tt.expected != "" {
// Remove the time for comparison
parts := strings.SplitN(actual, " ", 3)
require.Len(t, parts, 3)
actual = parts[2]
expected := deprecationPrefix(tt.level) + ": " + tt.expected
require.Equal(t, expected, actual)
} else {
Expand Down Expand Up @@ -160,10 +156,6 @@ func TestPluginOptionDeprecation(t *testing.T) {
}

if tt.expected != "" {
// Remove the time for comparison
parts := strings.SplitN(actual, " ", 3)
require.Len(t, parts, 3)
actual = parts[2]
expected := deprecationPrefix(tt.expectedLevel) + ": " + tt.expected
require.Equal(t, expected, actual)
} else {
Expand Down Expand Up @@ -259,9 +251,7 @@ func TestPluginOptionValueDeprecation(t *testing.T) {
}, timeout, 100*time.Millisecond)

// Remove the time for comparison
parts := strings.SplitN(strings.TrimSpace(buf.String()), " ", 3)
require.Len(t, parts, 3)
actual := parts[2]
actual := strings.TrimSpace(buf.String())
expected := deprecationPrefix(tt.expectedLevel) + ": " + tt.expected
require.Equal(t, expected, actual)
} else {
Expand Down
25 changes: 0 additions & 25 deletions logger/config.go

This file was deleted.

160 changes: 128 additions & 32 deletions logger/default_logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,28 @@ import (
"io"
"log"
"os"
"regexp"
"strings"
"time"

"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal/rotate"
"github.com/influxdata/wlog"
)

var prefixRegex = regexp.MustCompile("^[DIWE]!")

const (
LogTargetFile = "file"
LogTargetStderr = "stderr"
)

type defaultLogger struct {
Category string
Name string
Alias string
LogLevel telegraf.LogLevel

prefix string
onError []func()

writer io.Writer
internalWriter io.Writer
timezone *time.Location
Expand All @@ -39,6 +45,32 @@ func (t *defaultLogger) Write(b []byte) (n int, err error) {
return t.writer.Write(line)
}

// NewLogger creates a new logger instance
func (t *defaultLogger) New(category, name, alias string) telegraf.Logger {
var prefix string
if category != "" {
prefix = "[" + category
if name != "" {
prefix += "." + name
}
if alias != "" {
prefix += "::" + alias
}
prefix += "] "
}

return &defaultLogger{
Category: category,
Name: name,
Alias: alias,
LogLevel: t.LogLevel,
prefix: prefix,
writer: t.writer,
internalWriter: t.internalWriter,
timezone: t.timezone,
}
}

func (t *defaultLogger) Close() error {
// avoid closing stderr
if t.internalWriter == os.Stderr {
Expand All @@ -52,49 +84,113 @@ func (t *defaultLogger) Close() error {
return closer.Close()
}

// newTelegrafWriter returns a logging-wrapped writer.
func newTelegrafWriter(w io.Writer, c Config) (*defaultLogger, error) {
timezoneName := c.LogWithTimezone
if strings.EqualFold(timezoneName, "local") {
timezoneName = "Local"
// OnErr defines a callback that triggers only when errors are about to be written to the log
func (t *defaultLogger) RegisterErrorCallback(f func()) {
t.onError = append(t.onError, f)
}

func (t *defaultLogger) Level() telegraf.LogLevel {
return t.LogLevel
}

// Errorf logs an error message, patterned after log.Printf.
func (t *defaultLogger) Errorf(format string, args ...interface{}) {
log.Printf("E! "+t.prefix+format, args...)
for _, f := range t.onError {
f()
}
}

tz, err := time.LoadLocation(timezoneName)
if err != nil {
return nil, errors.New("error while setting logging timezone: " + err.Error())
// Error logs an error message, patterned after log.Print.
func (t *defaultLogger) Error(args ...interface{}) {
for _, f := range t.onError {
f()
}
log.Print(append([]interface{}{"E! " + t.prefix}, args...)...)
}

return &defaultLogger{
writer: wlog.NewWriter(w),
internalWriter: w,
timezone: tz,
}, nil
// Debugf logs a debug message, patterned after log.Printf.
func (t *defaultLogger) Debugf(format string, args ...interface{}) {
log.Printf("D! "+t.prefix+" "+format, args...)
}

// Debug logs a debug message, patterned after log.Print.
func (t *defaultLogger) Debug(args ...interface{}) {
log.Print(append([]interface{}{"D! " + t.prefix}, args...)...)
}

// Warnf logs a warning message, patterned after log.Printf.
func (t *defaultLogger) Warnf(format string, args ...interface{}) {
log.Printf("W! "+t.prefix+format, args...)
}

// Warn logs a warning message, patterned after log.Print.
func (t *defaultLogger) Warn(args ...interface{}) {
log.Print(append([]interface{}{"W! " + t.prefix}, args...)...)
}

// Infof logs an information message, patterned after log.Printf.
func (t *defaultLogger) Infof(format string, args ...interface{}) {
log.Printf("I! "+t.prefix+format, args...)
}

func createStderrLogger(cfg Config) (io.WriteCloser, error) {
return newTelegrafWriter(os.Stderr, cfg)
// Info logs an information message, patterned after log.Print.
func (t *defaultLogger) Info(args ...interface{}) {
log.Print(append([]interface{}{"I! " + t.prefix}, args...)...)
}

func createFileLogger(cfg Config) (io.WriteCloser, error) {
if cfg.Logfile == "" {
return createStderrLogger(cfg)
func createDefaultLogger(cfg *Config) (logger, error) {
log.SetFlags(0)

// Set the log-level
switch cfg.logLevel {
case telegraf.Error:
wlog.SetLevel(wlog.ERROR)
case telegraf.Warn:
wlog.SetLevel(wlog.WARN)
case telegraf.Info:
wlog.SetLevel(wlog.INFO)
case telegraf.Debug:
wlog.SetLevel(wlog.DEBUG)
}

writer, err := rotate.NewFileWriter(
cfg.Logfile,
cfg.RotationInterval,
cfg.RotationMaxSize,
cfg.RotationMaxArchives,
)
// Setup the writer target
var writer io.Writer = os.Stderr
if cfg.LogTarget == "file" && cfg.Logfile != "" {
w, err := rotate.NewFileWriter(
cfg.Logfile,
cfg.RotationInterval,
cfg.RotationMaxSize,
cfg.RotationMaxArchives,
)
if err != nil {
return nil, err
}
writer = w
}

// Get configured timezone
timezoneName := cfg.LogWithTimezone
if strings.EqualFold(timezoneName, "local") {
timezoneName = "Local"
}
tz, err := time.LoadLocation(timezoneName)
if err != nil {
log.Printf("E! Unable to open %s (%s), using stderr", cfg.Logfile, err)
return createStderrLogger(cfg)
return nil, errors.New("error while setting logging timezone: " + err.Error())
}

// Setup the logger
l := &defaultLogger{
writer: wlog.NewWriter(writer),
internalWriter: writer,
timezone: tz,
}

return newTelegrafWriter(writer, cfg)
log.SetOutput(l)
return l, nil
}

func init() {
registerLogger(LogTargetStderr, createStderrLogger)
registerLogger(LogTargetFile, createFileLogger)
add("stderr", createDefaultLogger)
add("file", createDefaultLogger)
}
Loading

0 comments on commit 32a5b44

Please sign in to comment.