chore(log): Restructure and cleanup logging code (#15234)
This commit is contained in:
parent
e7703ae9c0
commit
71b58ddaf5
|
|
@ -11,7 +11,7 @@ import (
|
|||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/models"
|
||||
"github.com/influxdata/telegraf/logger"
|
||||
)
|
||||
|
||||
func TestAddFields(t *testing.T) {
|
||||
|
|
@ -156,5 +156,5 @@ func (tm *TestMetricMaker) MakeMetric(metric telegraf.Metric) telegraf.Metric {
|
|||
}
|
||||
|
||||
func (tm *TestMetricMaker) Log() telegraf.Logger {
|
||||
return models.NewLogger("TestPlugin", "test", "")
|
||||
return logger.NewLogger("TestPlugin", "test", "")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,11 +10,11 @@ import (
|
|||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/urfave/cli/v2"
|
||||
|
||||
"github.com/influxdata/telegraf/config"
|
||||
"github.com/influxdata/telegraf/logger"
|
||||
"github.com/influxdata/telegraf/migrations"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
|
||||
func getConfigCommands(pluginFilterFlags []cli.Flag, outputBuffer io.Writer) []*cli.Command {
|
||||
|
|
@ -84,8 +84,7 @@ To migrate the file 'mysettings.conf' use
|
|||
},
|
||||
Action: func(cCtx *cli.Context) error {
|
||||
// Setup logging
|
||||
telegraf.Debug = cCtx.Bool("debug")
|
||||
logConfig := logger.LogConfig{Debug: telegraf.Debug}
|
||||
logConfig := logger.Config{Debug: cCtx.Bool("debug")}
|
||||
if err := logger.SetupLogging(logConfig); err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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.LogConfig{})
|
||||
err := logger.SetupLogging(logger.Config{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
@ -372,6 +372,7 @@ func runApp(args []string, outputBuffer io.Writer, pprof Server, c TelegrafConfi
|
|||
|
||||
// Make sure we safely erase secrets
|
||||
defer memguard.Purge()
|
||||
defer logger.CloseLogging()
|
||||
|
||||
return app.Run(args)
|
||||
}
|
||||
|
|
@ -383,8 +384,7 @@ func main() {
|
|||
agent := Telegraf{}
|
||||
pprof := NewPprofServer()
|
||||
c := config.NewConfig()
|
||||
err := runApp(os.Args, os.Stdout, pprof, c, &agent)
|
||||
if err != nil {
|
||||
if err := runApp(os.Args, os.Stdout, pprof, c, &agent); err != nil {
|
||||
log.Fatalf("E! %s", err)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -279,14 +279,13 @@ func (t *Telegraf) runAgent(ctx context.Context, c *config.Config, reloadConfig
|
|||
}
|
||||
|
||||
// Setup logging as configured.
|
||||
telegraf.Debug = c.Agent.Debug || t.debug
|
||||
logConfig := logger.LogConfig{
|
||||
Debug: telegraf.Debug,
|
||||
logConfig := logger.Config{
|
||||
Debug: c.Agent.Debug || t.debug,
|
||||
Quiet: c.Agent.Quiet || t.quiet,
|
||||
LogTarget: c.Agent.LogTarget,
|
||||
Logfile: c.Agent.Logfile,
|
||||
RotationInterval: c.Agent.LogfileRotationInterval,
|
||||
RotationMaxSize: c.Agent.LogfileRotationMaxSize,
|
||||
RotationInterval: time.Duration(c.Agent.LogfileRotationInterval),
|
||||
RotationMaxSize: int64(c.Agent.LogfileRotationMaxSize),
|
||||
RotationMaxArchives: c.Agent.LogfileRotationMaxArchives,
|
||||
LogWithTimezone: c.Agent.LogWithTimezone,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -144,7 +144,7 @@ func (t *Telegraf) runAsWindowsService() error {
|
|||
return err
|
||||
}
|
||||
} else {
|
||||
err = logger.SetupLogging(logger.LogConfig{LogTarget: logger.LogTargetEventlog})
|
||||
err = logger.SetupLogging(logger.Config{LogTarget: "eventlog"})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ import (
|
|||
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/internal"
|
||||
logging "github.com/influxdata/telegraf/logger"
|
||||
"github.com/influxdata/telegraf/models"
|
||||
"github.com/influxdata/telegraf/persister"
|
||||
"github.com/influxdata/telegraf/plugins/aggregators"
|
||||
|
|
@ -54,6 +55,9 @@ var (
|
|||
|
||||
// Password specified via command-line
|
||||
Password Secret
|
||||
|
||||
// telegrafVersion contains the parsed semantic Telegraf version
|
||||
telegrafVersion *semver.Version = semver.New("0.0.0-unknown")
|
||||
)
|
||||
|
||||
// Config specifies the URL/user/password for the database that telegraf
|
||||
|
|
@ -86,7 +90,6 @@ type Config struct {
|
|||
// like the other plugins because they need to be garbage collected (See issue #11809)
|
||||
|
||||
Deprecations map[string][]int64
|
||||
version *semver.Version
|
||||
|
||||
Persister *persister.Persister
|
||||
|
||||
|
|
@ -136,11 +139,9 @@ func NewConfig() *Config {
|
|||
}
|
||||
|
||||
// Handle unknown version
|
||||
version := internal.Version
|
||||
if version == "" || version == "unknown" {
|
||||
version = "0.0.0-unknown"
|
||||
if internal.Version != "" && internal.Version != "unknown" {
|
||||
telegrafVersion = semver.New(internal.Version)
|
||||
}
|
||||
c.version = semver.New(version)
|
||||
|
||||
tomlCfg := &toml.Config{
|
||||
NormFieldName: toml.DefaultConfig.NormFieldName,
|
||||
|
|
@ -535,7 +536,7 @@ func (c *Config) LoadConfigData(data []byte) error {
|
|||
|
||||
// Warn when explicitly setting the old snmp translator
|
||||
if c.Agent.SnmpTranslator == "netsnmp" {
|
||||
models.PrintOptionValueDeprecationNotice(telegraf.Warn, "agent", "snmp_translator", "netsnmp", telegraf.DeprecationInfo{
|
||||
PrintOptionValueDeprecationNotice("agent", "snmp_translator", "netsnmp", telegraf.DeprecationInfo{
|
||||
Since: "1.25.0",
|
||||
RemovalIn: "2.0.0",
|
||||
Notice: "Use 'gosmi' instead",
|
||||
|
|
@ -871,7 +872,7 @@ func (c *Config) addSecretStore(name string, table *ast.Table) error {
|
|||
return err
|
||||
}
|
||||
|
||||
logger := models.NewLogger("secretstores", name, "")
|
||||
logger := logging.NewLogger("secretstores", name, "")
|
||||
models.SetLoggerOnPlugin(store, logger)
|
||||
|
||||
if err := store.Init(); err != nil {
|
||||
|
|
@ -1359,7 +1360,7 @@ func (c *Config) buildFilter(plugin string, tbl *ast.Table) (models.Filter, erro
|
|||
var oldPass []string
|
||||
c.getFieldStringSlice(tbl, "pass", &oldPass)
|
||||
if len(oldPass) > 0 {
|
||||
models.PrintOptionDeprecationNotice(telegraf.Warn, plugin, "pass", telegraf.DeprecationInfo{
|
||||
PrintOptionDeprecationNotice(plugin, "pass", telegraf.DeprecationInfo{
|
||||
Since: "0.10.4",
|
||||
RemovalIn: "2.0.0",
|
||||
Notice: "use 'fieldinclude' instead",
|
||||
|
|
@ -1369,7 +1370,7 @@ func (c *Config) buildFilter(plugin string, tbl *ast.Table) (models.Filter, erro
|
|||
var oldFieldPass []string
|
||||
c.getFieldStringSlice(tbl, "fieldpass", &oldFieldPass)
|
||||
if len(oldFieldPass) > 0 {
|
||||
models.PrintOptionDeprecationNotice(telegraf.Warn, plugin, "fieldpass", telegraf.DeprecationInfo{
|
||||
PrintOptionDeprecationNotice(plugin, "fieldpass", telegraf.DeprecationInfo{
|
||||
Since: "1.29.0",
|
||||
RemovalIn: "2.0.0",
|
||||
Notice: "use 'fieldinclude' instead",
|
||||
|
|
@ -1381,7 +1382,7 @@ func (c *Config) buildFilter(plugin string, tbl *ast.Table) (models.Filter, erro
|
|||
var oldDrop []string
|
||||
c.getFieldStringSlice(tbl, "drop", &oldDrop)
|
||||
if len(oldDrop) > 0 {
|
||||
models.PrintOptionDeprecationNotice(telegraf.Warn, plugin, "drop", telegraf.DeprecationInfo{
|
||||
PrintOptionDeprecationNotice(plugin, "drop", telegraf.DeprecationInfo{
|
||||
Since: "0.10.4",
|
||||
RemovalIn: "2.0.0",
|
||||
Notice: "use 'fieldexclude' instead",
|
||||
|
|
@ -1391,7 +1392,7 @@ func (c *Config) buildFilter(plugin string, tbl *ast.Table) (models.Filter, erro
|
|||
var oldFieldDrop []string
|
||||
c.getFieldStringSlice(tbl, "fielddrop", &oldFieldDrop)
|
||||
if len(oldFieldDrop) > 0 {
|
||||
models.PrintOptionDeprecationNotice(telegraf.Warn, plugin, "fielddrop", telegraf.DeprecationInfo{
|
||||
PrintOptionDeprecationNotice(plugin, "fielddrop", telegraf.DeprecationInfo{
|
||||
Since: "1.29.0",
|
||||
RemovalIn: "2.0.0",
|
||||
Notice: "use 'fieldexclude' instead",
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ import (
|
|||
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/config"
|
||||
logging "github.com/influxdata/telegraf/logger"
|
||||
"github.com/influxdata/telegraf/metric"
|
||||
"github.com/influxdata/telegraf/models"
|
||||
"github.com/influxdata/telegraf/persister"
|
||||
|
|
@ -637,7 +638,7 @@ func TestConfig_SerializerInterfaceNewFormat(t *testing.T) {
|
|||
formatCfg := &cfg
|
||||
formatCfg.DataFormat = format
|
||||
|
||||
logger := models.NewLogger("serializers", format, "test")
|
||||
logger := logging.NewLogger("serializers", format, "test")
|
||||
|
||||
var serializer telegraf.Serializer
|
||||
if creator, found := serializers.Serializers[format]; found {
|
||||
|
|
@ -729,7 +730,7 @@ func TestConfig_SerializerInterfaceOldFormat(t *testing.T) {
|
|||
formatCfg := &cfg
|
||||
formatCfg.DataFormat = format
|
||||
|
||||
logger := models.NewLogger("serializers", format, "test")
|
||||
logger := logging.NewLogger("serializers", format, "test")
|
||||
|
||||
var serializer serializers.Serializer
|
||||
if creator, found := serializers.Serializers[format]; found {
|
||||
|
|
@ -835,7 +836,7 @@ func TestConfig_ParserInterface(t *testing.T) {
|
|||
|
||||
expected := make([]telegraf.Parser, 0, len(formats))
|
||||
for _, format := range formats {
|
||||
logger := models.NewLogger("parsers", format, "parser_test_new")
|
||||
logger := logging.NewLogger("parsers", format, "parser_test_new")
|
||||
|
||||
creator, found := parsers.Parsers[format]
|
||||
require.Truef(t, found, "No parser for format %q", format)
|
||||
|
|
@ -1041,7 +1042,7 @@ func TestConfig_ProcessorsWithParsers(t *testing.T) {
|
|||
|
||||
expected := make([]telegraf.Parser, 0, len(formats))
|
||||
for _, format := range formats {
|
||||
logger := models.NewLogger("parsers", format, "processors_with_parsers")
|
||||
logger := logging.NewLogger("parsers", format, "processors_with_parsers")
|
||||
|
||||
creator, found := parsers.Parsers[format]
|
||||
require.Truef(t, found, "No parser for format %q", format)
|
||||
|
|
|
|||
|
|
@ -12,7 +12,6 @@ import (
|
|||
"github.com/fatih/color"
|
||||
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/models"
|
||||
"github.com/influxdata/telegraf/plugins/aggregators"
|
||||
"github.com/influxdata/telegraf/plugins/inputs"
|
||||
"github.com/influxdata/telegraf/plugins/outputs"
|
||||
|
|
@ -24,12 +23,12 @@ type DeprecationInfo struct {
|
|||
// Name of the plugin or plugin option
|
||||
Name string
|
||||
// LogLevel is the level of deprecation which currently corresponds to a log-level
|
||||
LogLevel telegraf.Escalation
|
||||
logLevel telegraf.LogLevel
|
||||
info telegraf.DeprecationInfo
|
||||
}
|
||||
|
||||
func (di *DeprecationInfo) determineEscalation(telegrafVersion *semver.Version) error {
|
||||
di.LogLevel = telegraf.None
|
||||
func (di *DeprecationInfo) determineEscalation() error {
|
||||
di.logLevel = telegraf.None
|
||||
if di.info.Since == "" {
|
||||
return nil
|
||||
}
|
||||
|
|
@ -58,9 +57,9 @@ func (di *DeprecationInfo) determineEscalation(telegrafVersion *semver.Version)
|
|||
Patch: telegrafVersion.Patch,
|
||||
}
|
||||
if !version.LessThan(*removal) {
|
||||
di.LogLevel = telegraf.Error
|
||||
di.logLevel = telegraf.Error
|
||||
} else if !version.LessThan(*since) {
|
||||
di.LogLevel = telegraf.Warn
|
||||
di.logLevel = telegraf.Warn
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -93,7 +92,7 @@ func (c *Config) collectDeprecationInfo(category, name string, plugin interface{
|
|||
info := PluginDeprecationInfo{
|
||||
DeprecationInfo: DeprecationInfo{
|
||||
Name: category + "." + name,
|
||||
LogLevel: telegraf.None,
|
||||
logLevel: telegraf.None,
|
||||
},
|
||||
}
|
||||
|
||||
|
|
@ -116,10 +115,10 @@ func (c *Config) collectDeprecationInfo(category, name string, plugin interface{
|
|||
info.DeprecationInfo.info = pi
|
||||
}
|
||||
}
|
||||
if err := info.determineEscalation(c.version); err != nil {
|
||||
if err := info.determineEscalation(); err != nil {
|
||||
panic(fmt.Errorf("plugin %q: %w", info.Name, err))
|
||||
}
|
||||
if info.LogLevel != telegraf.None {
|
||||
if info.logLevel != telegraf.None {
|
||||
c.incrementPluginDeprecations(category)
|
||||
}
|
||||
|
||||
|
|
@ -148,11 +147,11 @@ func (c *Config) collectDeprecationInfo(category, name string, plugin interface{
|
|||
if len(tags) > 2 {
|
||||
optionInfo.info.RemovalIn = tags[1]
|
||||
}
|
||||
if err := optionInfo.determineEscalation(c.version); err != nil {
|
||||
if err := optionInfo.determineEscalation(); err != nil {
|
||||
panic(fmt.Errorf("plugin %q option %q: %w", info.Name, field.Name, err))
|
||||
}
|
||||
|
||||
if optionInfo.LogLevel != telegraf.None {
|
||||
if optionInfo.logLevel != telegraf.None {
|
||||
c.incrementPluginOptionDeprecations(category)
|
||||
}
|
||||
|
||||
|
|
@ -169,17 +168,17 @@ func (c *Config) collectDeprecationInfo(category, name string, plugin interface{
|
|||
|
||||
func (c *Config) printUserDeprecation(category, name string, plugin interface{}) error {
|
||||
info := c.collectDeprecationInfo(category, name, plugin, false)
|
||||
models.PrintPluginDeprecationNotice(info.LogLevel, info.Name, info.info)
|
||||
printPluginDeprecationNotice(info.logLevel, info.Name, info.info)
|
||||
|
||||
if info.LogLevel == telegraf.Error {
|
||||
if info.logLevel == telegraf.Error {
|
||||
return errors.New("plugin deprecated")
|
||||
}
|
||||
|
||||
// Print deprecated options
|
||||
deprecatedOptions := make([]string, 0)
|
||||
for _, option := range info.Options {
|
||||
models.PrintOptionDeprecationNotice(option.LogLevel, info.Name, option.Name, option.info)
|
||||
if option.LogLevel == telegraf.Error {
|
||||
PrintOptionDeprecationNotice(info.Name, option.Name, option.info)
|
||||
if option.logLevel == telegraf.Error {
|
||||
deprecatedOptions = append(deprecatedOptions, option.Name)
|
||||
}
|
||||
}
|
||||
|
|
@ -203,7 +202,7 @@ func (c *Config) CollectDeprecationInfos(inFilter, outFilter, aggFilter, procFil
|
|||
plugin := creator()
|
||||
info := c.collectDeprecationInfo("inputs", name, plugin, true)
|
||||
|
||||
if info.LogLevel != telegraf.None || len(info.Options) > 0 {
|
||||
if info.logLevel != telegraf.None || len(info.Options) > 0 {
|
||||
infos["inputs"] = append(infos["inputs"], info)
|
||||
}
|
||||
}
|
||||
|
|
@ -217,7 +216,7 @@ func (c *Config) CollectDeprecationInfos(inFilter, outFilter, aggFilter, procFil
|
|||
plugin := creator()
|
||||
info := c.collectDeprecationInfo("outputs", name, plugin, true)
|
||||
|
||||
if info.LogLevel != telegraf.None || len(info.Options) > 0 {
|
||||
if info.logLevel != telegraf.None || len(info.Options) > 0 {
|
||||
infos["outputs"] = append(infos["outputs"], info)
|
||||
}
|
||||
}
|
||||
|
|
@ -231,7 +230,7 @@ func (c *Config) CollectDeprecationInfos(inFilter, outFilter, aggFilter, procFil
|
|||
plugin := creator()
|
||||
info := c.collectDeprecationInfo("processors", name, plugin, true)
|
||||
|
||||
if info.LogLevel != telegraf.None || len(info.Options) > 0 {
|
||||
if info.logLevel != telegraf.None || len(info.Options) > 0 {
|
||||
infos["processors"] = append(infos["processors"], info)
|
||||
}
|
||||
}
|
||||
|
|
@ -245,7 +244,7 @@ func (c *Config) CollectDeprecationInfos(inFilter, outFilter, aggFilter, procFil
|
|||
plugin := creator()
|
||||
info := c.collectDeprecationInfo("aggregators", name, plugin, true)
|
||||
|
||||
if info.LogLevel != telegraf.None || len(info.Options) > 0 {
|
||||
if info.logLevel != telegraf.None || len(info.Options) > 0 {
|
||||
infos["aggregators"] = append(infos["aggregators"], info)
|
||||
}
|
||||
}
|
||||
|
|
@ -257,11 +256,11 @@ func (c *Config) PrintDeprecationList(plugins []PluginDeprecationInfo) {
|
|||
sort.Slice(plugins, func(i, j int) bool { return plugins[i].Name < plugins[j].Name })
|
||||
|
||||
for _, plugin := range plugins {
|
||||
switch plugin.LogLevel {
|
||||
switch plugin.logLevel {
|
||||
case telegraf.Warn, telegraf.Error:
|
||||
fmt.Printf(
|
||||
" %-40s %-5s since %-5s removal in %-5s %s\n",
|
||||
plugin.Name, plugin.LogLevel, plugin.info.Since, plugin.info.RemovalIn, plugin.info.Notice,
|
||||
plugin.Name, plugin.logLevel, plugin.info.Since, plugin.info.RemovalIn, plugin.info.Notice,
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -272,7 +271,7 @@ func (c *Config) PrintDeprecationList(plugins []PluginDeprecationInfo) {
|
|||
for _, option := range plugin.Options {
|
||||
fmt.Printf(
|
||||
" %-40s %-5s since %-5s removal in %-5s %s\n",
|
||||
plugin.Name+"/"+option.Name, option.LogLevel, option.info.Since, option.info.RemovalIn, option.info.Notice,
|
||||
plugin.Name+"/"+option.Name, option.logLevel, option.info.Since, option.info.RemovalIn, option.info.Notice,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -329,3 +328,67 @@ func walkPluginStruct(value reflect.Value, fn func(f reflect.StructField, fv ref
|
|||
fn(field, fieldValue)
|
||||
}
|
||||
}
|
||||
|
||||
func deprecationPrefix(level telegraf.LogLevel) string {
|
||||
switch level {
|
||||
case telegraf.Warn:
|
||||
return "W! " + color.YellowString("DeprecationWarning")
|
||||
case telegraf.Error:
|
||||
return "E! " + color.RedString("DeprecationError")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func printPluginDeprecationNotice(level telegraf.LogLevel, name string, info telegraf.DeprecationInfo) {
|
||||
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,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func PrintOptionDeprecationNotice(plugin, option string, info telegraf.DeprecationInfo) {
|
||||
// Determine the log-level
|
||||
di := &DeprecationInfo{
|
||||
Name: plugin,
|
||||
info: info,
|
||||
}
|
||||
if err := di.determineEscalation(); err != nil {
|
||||
log.Printf("E! Determining log-level for option %s in plugin %s failed: %v", option, plugin, err)
|
||||
return
|
||||
}
|
||||
|
||||
switch di.logLevel {
|
||||
case telegraf.Warn, telegraf.Error:
|
||||
prefix := deprecationPrefix(di.logLevel)
|
||||
log.Printf(
|
||||
"%s: Option %q of plugin %q deprecated since version %s and will be removed in %s: %s",
|
||||
prefix, option, plugin, info.Since, info.RemovalIn, info.Notice,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func PrintOptionValueDeprecationNotice(plugin, option string, value interface{}, info telegraf.DeprecationInfo) {
|
||||
// Determine the log-level
|
||||
di := &DeprecationInfo{
|
||||
Name: plugin,
|
||||
info: info,
|
||||
}
|
||||
if err := di.determineEscalation(); err != nil {
|
||||
log.Printf("E! Determining log-level for option %s in plugin %s failed: %v", option, plugin, err)
|
||||
return
|
||||
}
|
||||
|
||||
switch di.logLevel {
|
||||
case telegraf.Warn, telegraf.Error:
|
||||
prefix := deprecationPrefix(di.logLevel)
|
||||
log.Printf(
|
||||
`%s: Value "%+v" for option %q of plugin %q deprecated since version %s and will be removed in %s: %s`,
|
||||
prefix, value, option, plugin, info.Since, info.RemovalIn, info.Notice,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
package models
|
||||
package config
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
|
|
@ -8,27 +8,11 @@ import (
|
|||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/coreos/go-semver/semver"
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/selfstat"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestErrorCounting(t *testing.T) {
|
||||
reg := selfstat.Register(
|
||||
"gather",
|
||||
"errors",
|
||||
map[string]string{"input": "test"},
|
||||
)
|
||||
iLog := Logger{Name: "inputs.test"}
|
||||
iLog.OnErr(func() {
|
||||
reg.Incr(1)
|
||||
})
|
||||
iLog.Error("something went wrong")
|
||||
iLog.Errorf("something went wrong")
|
||||
|
||||
require.Equal(t, int64(2), reg.Get())
|
||||
}
|
||||
|
||||
func TestPluginDeprecation(t *testing.T) {
|
||||
info := telegraf.DeprecationInfo{
|
||||
Since: "1.23.0",
|
||||
|
|
@ -37,7 +21,7 @@ func TestPluginDeprecation(t *testing.T) {
|
|||
}
|
||||
var tests = []struct {
|
||||
name string
|
||||
level telegraf.Escalation
|
||||
level telegraf.LogLevel
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
|
|
@ -69,7 +53,7 @@ func TestPluginDeprecation(t *testing.T) {
|
|||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
buf.Reset()
|
||||
PrintPluginDeprecationNotice(tt.level, "test", info)
|
||||
printPluginDeprecationNotice(tt.level, "test", info)
|
||||
|
||||
// Wait for a newline to arrive and timeout for cases where
|
||||
// we don't see a message.
|
||||
|
|
@ -105,33 +89,39 @@ func TestPluginDeprecation(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestPluginOptionDeprecation(t *testing.T) {
|
||||
info := telegraf.DeprecationInfo{
|
||||
Since: "1.23.0",
|
||||
RemovalIn: "2.0.0",
|
||||
Notice: "please check",
|
||||
}
|
||||
var tests = []struct {
|
||||
name string
|
||||
level telegraf.Escalation
|
||||
expected string
|
||||
name string
|
||||
since string
|
||||
removal string
|
||||
expected string
|
||||
expectedLevel telegraf.LogLevel
|
||||
}{
|
||||
{
|
||||
name: "Error level",
|
||||
level: telegraf.Error,
|
||||
expected: `Option "option" of plugin "test" deprecated since version 1.23.0 and will be removed in 2.0.0: please check`,
|
||||
name: "Error level",
|
||||
since: "1.23.0",
|
||||
removal: "1.29.0",
|
||||
expectedLevel: telegraf.Error,
|
||||
expected: `Option "option" of plugin "test" deprecated since version 1.23.0 and will be removed in 1.29.0: please check`,
|
||||
},
|
||||
{
|
||||
name: "Warn level",
|
||||
level: telegraf.Warn,
|
||||
expected: `Option "option" of plugin "test" deprecated since version 1.23.0 and will be removed in 2.0.0: please check`,
|
||||
name: "Warn level",
|
||||
since: "1.23.0",
|
||||
removal: "2.0.0",
|
||||
expectedLevel: telegraf.Warn,
|
||||
expected: `Option "option" of plugin "test" deprecated since version 1.23.0 and will be removed in 2.0.0: please check`,
|
||||
},
|
||||
{
|
||||
name: "None",
|
||||
level: telegraf.None,
|
||||
expected: ``,
|
||||
name: "None",
|
||||
expectedLevel: telegraf.None,
|
||||
expected: ``,
|
||||
},
|
||||
}
|
||||
|
||||
// Fake telegraf's version
|
||||
version, err := semver.NewVersion("1.30.0")
|
||||
require.NoError(t, err)
|
||||
telegrafVersion = version
|
||||
|
||||
// Switch the logger to log to a buffer
|
||||
var buf bytes.Buffer
|
||||
scanner := bufio.NewScanner(&buf)
|
||||
|
|
@ -144,7 +134,12 @@ func TestPluginOptionDeprecation(t *testing.T) {
|
|||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
buf.Reset()
|
||||
PrintOptionDeprecationNotice(tt.level, "test", "option", info)
|
||||
info := telegraf.DeprecationInfo{
|
||||
Since: tt.since,
|
||||
RemovalIn: tt.removal,
|
||||
Notice: "please check",
|
||||
}
|
||||
PrintOptionDeprecationNotice("test", "option", info)
|
||||
// Wait for a newline to arrive and timeout for cases where
|
||||
// we don't see a message.
|
||||
go func() {
|
||||
|
|
@ -169,7 +164,7 @@ func TestPluginOptionDeprecation(t *testing.T) {
|
|||
parts := strings.SplitN(actual, " ", 3)
|
||||
require.Len(t, parts, 3)
|
||||
actual = parts[2]
|
||||
expected := deprecationPrefix(tt.level) + ": " + tt.expected
|
||||
expected := deprecationPrefix(tt.expectedLevel) + ": " + tt.expected
|
||||
require.Equal(t, expected, actual)
|
||||
} else {
|
||||
require.Empty(t, actual)
|
||||
|
|
@ -179,54 +174,66 @@ func TestPluginOptionDeprecation(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestPluginOptionValueDeprecation(t *testing.T) {
|
||||
info := telegraf.DeprecationInfo{
|
||||
Since: "1.25.0",
|
||||
RemovalIn: "2.0.0",
|
||||
Notice: "please check",
|
||||
}
|
||||
var tests = []struct {
|
||||
name string
|
||||
level telegraf.Escalation
|
||||
value interface{}
|
||||
expected string
|
||||
name string
|
||||
since string
|
||||
removal string
|
||||
value interface{}
|
||||
expected string
|
||||
expectedLevel telegraf.LogLevel
|
||||
}{
|
||||
{
|
||||
name: "Error level",
|
||||
level: telegraf.Error,
|
||||
value: "foobar",
|
||||
expected: `Value "foobar" for option "option" of plugin "test" deprecated since version 1.25.0 and will be removed in 2.0.0: please check`,
|
||||
name: "Error level",
|
||||
since: "1.25.0",
|
||||
removal: "1.29.0",
|
||||
value: "foobar",
|
||||
expected: `Value "foobar" for option "option" of plugin "test" deprecated since version 1.25.0 and will be removed in 1.29.0: please check`,
|
||||
expectedLevel: telegraf.Error,
|
||||
},
|
||||
{
|
||||
name: "Warn level",
|
||||
level: telegraf.Warn,
|
||||
value: "foobar",
|
||||
expected: `Value "foobar" for option "option" of plugin "test" deprecated since version 1.25.0 and will be removed in 2.0.0: please check`,
|
||||
name: "Warn level",
|
||||
since: "1.25.0",
|
||||
removal: "2.0.0",
|
||||
value: "foobar",
|
||||
expected: `Value "foobar" for option "option" of plugin "test" deprecated since version 1.25.0 and will be removed in 2.0.0: please check`,
|
||||
expectedLevel: telegraf.Warn,
|
||||
},
|
||||
{
|
||||
name: "None",
|
||||
level: telegraf.None,
|
||||
expected: ``,
|
||||
name: "None",
|
||||
expected: ``,
|
||||
expectedLevel: telegraf.None,
|
||||
},
|
||||
{
|
||||
name: "nil value",
|
||||
level: telegraf.Error,
|
||||
value: nil,
|
||||
expected: `Value "<nil>" for option "option" of plugin "test" deprecated since version 1.25.0 and will be removed in 2.0.0: please check`,
|
||||
name: "nil value",
|
||||
since: "1.25.0",
|
||||
removal: "1.29.0",
|
||||
value: nil,
|
||||
expected: `Value "<nil>" for option "option" of plugin "test" deprecated since version 1.25.0 and will be removed in 1.29.0: please check`,
|
||||
expectedLevel: telegraf.Error,
|
||||
},
|
||||
{
|
||||
name: "Boolean value",
|
||||
level: telegraf.Error,
|
||||
value: true,
|
||||
expected: `Value "true" for option "option" of plugin "test" deprecated since version 1.25.0 and will be removed in 2.0.0: please check`,
|
||||
name: "Boolean value",
|
||||
since: "1.25.0",
|
||||
removal: "1.29.0",
|
||||
value: true,
|
||||
expected: `Value "true" for option "option" of plugin "test" deprecated since version 1.25.0 and will be removed in 1.29.0: please check`,
|
||||
expectedLevel: telegraf.Error,
|
||||
},
|
||||
{
|
||||
name: "Integer value",
|
||||
level: telegraf.Error,
|
||||
value: 123,
|
||||
expected: `Value "123" for option "option" of plugin "test" deprecated since version 1.25.0 and will be removed in 2.0.0: please check`,
|
||||
name: "Integer value",
|
||||
since: "1.25.0",
|
||||
removal: "1.29.0",
|
||||
value: 123,
|
||||
expected: `Value "123" for option "option" of plugin "test" deprecated since version 1.25.0 and will be removed in 1.29.0: please check`,
|
||||
expectedLevel: telegraf.Error,
|
||||
},
|
||||
}
|
||||
|
||||
// Fake telegraf's version
|
||||
version, err := semver.NewVersion("1.30.0")
|
||||
require.NoError(t, err)
|
||||
telegrafVersion = version
|
||||
|
||||
// Switch the logger to log to a buffer
|
||||
var buf bytes.Buffer
|
||||
previous := log.Writer()
|
||||
|
|
@ -238,7 +245,13 @@ func TestPluginOptionValueDeprecation(t *testing.T) {
|
|||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
buf.Reset()
|
||||
PrintOptionValueDeprecationNotice(tt.level, "test", "option", tt.value, info)
|
||||
|
||||
info := telegraf.DeprecationInfo{
|
||||
Since: tt.since,
|
||||
RemovalIn: tt.removal,
|
||||
Notice: "please check",
|
||||
}
|
||||
PrintOptionValueDeprecationNotice("test", "option", tt.value, info)
|
||||
|
||||
if tt.expected != "" {
|
||||
require.Eventually(t, func() bool {
|
||||
|
|
@ -249,7 +262,7 @@ func TestPluginOptionValueDeprecation(t *testing.T) {
|
|||
parts := strings.SplitN(strings.TrimSpace(buf.String()), " ", 3)
|
||||
require.Len(t, parts, 3)
|
||||
actual := parts[2]
|
||||
expected := deprecationPrefix(tt.level) + ": " + tt.expected
|
||||
expected := deprecationPrefix(tt.expectedLevel) + ": " + tt.expected
|
||||
require.Equal(t, expected, actual)
|
||||
} else {
|
||||
time.Sleep(timeout)
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
package telegraf
|
||||
|
||||
// LogLevel denotes the level for logging
|
||||
type LogLevel int
|
||||
|
||||
func (e LogLevel) String() string {
|
||||
switch e {
|
||||
case Error:
|
||||
return "ERROR"
|
||||
case Warn:
|
||||
return "WARN"
|
||||
case Info:
|
||||
return "INFO"
|
||||
case Debug:
|
||||
return "DEBUG"
|
||||
}
|
||||
return "NONE"
|
||||
}
|
||||
|
||||
const (
|
||||
// None means nothing is logged
|
||||
None LogLevel = iota
|
||||
// Error will log error messages
|
||||
Error
|
||||
// Warn will log error messages and warnings
|
||||
Warn
|
||||
// Info will log error messages, warnings and information messages
|
||||
Info
|
||||
// Debug will log all of the above and debugging messages issued by plugins
|
||||
Debug
|
||||
)
|
||||
|
||||
// Logger defines an plugin-related interface for logging.
|
||||
type Logger interface {
|
||||
// Level returns the configured log-level of the logger
|
||||
Level() LogLevel
|
||||
|
||||
// RegisterErrorCallback registers a callback triggered when logging errors
|
||||
RegisterErrorCallback(func())
|
||||
|
||||
// Errorf logs an error message, patterned after log.Printf.
|
||||
Errorf(format string, args ...interface{})
|
||||
// Error logs an error message, patterned after log.Print.
|
||||
Error(args ...interface{})
|
||||
// Debugf logs a debug message, patterned after log.Printf.
|
||||
Debugf(format string, args ...interface{})
|
||||
// Debug logs a debug message, patterned after log.Print.
|
||||
Debug(args ...interface{})
|
||||
// Warnf logs a warning message, patterned after log.Printf.
|
||||
Warnf(format string, args ...interface{})
|
||||
// Warn logs a warning message, patterned after log.Print.
|
||||
Warn(args ...interface{})
|
||||
// Infof logs an information message, patterned after log.Printf.
|
||||
Infof(format string, args ...interface{})
|
||||
// Info logs an information message, patterned after log.Print.
|
||||
Info(args ...interface{})
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
package logger
|
||||
|
||||
import "time"
|
||||
|
||||
// Config contains the log configuration settings
|
||||
type Config struct {
|
||||
// will set the log level to DEBUG
|
||||
Debug bool
|
||||
//will set the log level to ERROR
|
||||
Quiet bool
|
||||
//stderr, stdout, file or eventlog (Windows only)
|
||||
LogTarget string
|
||||
// will direct the logging output to a file. Empty string is
|
||||
// interpreted as stderr. If there is an error opening the file the
|
||||
// logger will fall back to stderr
|
||||
Logfile string
|
||||
// will rotate when current file at the specified time interval
|
||||
RotationInterval time.Duration
|
||||
// will rotate when current file size exceeds this parameter.
|
||||
RotationMaxSize int64
|
||||
// maximum rotated files to keep (older ones will be deleted)
|
||||
RotationMaxArchives int
|
||||
// pick a timezone to use when logging. or type 'local' for local time.
|
||||
LogWithTimezone string
|
||||
}
|
||||
|
|
@ -0,0 +1,95 @@
|
|||
package logger
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/influxdata/telegraf/internal/rotate"
|
||||
"github.com/influxdata/wlog"
|
||||
)
|
||||
|
||||
var prefixRegex = regexp.MustCompile("^[DIWE]!")
|
||||
|
||||
type defaultLogger struct {
|
||||
writer io.Writer
|
||||
internalWriter io.Writer
|
||||
timezone *time.Location
|
||||
}
|
||||
|
||||
func (t *defaultLogger) Write(b []byte) (n int, err error) {
|
||||
var line []byte
|
||||
timeToPrint := time.Now().In(t.timezone)
|
||||
|
||||
if !prefixRegex.Match(b) {
|
||||
line = append([]byte(timeToPrint.Format(time.RFC3339)+" I! "), b...)
|
||||
} else {
|
||||
line = append([]byte(timeToPrint.Format(time.RFC3339)+" "), b...)
|
||||
}
|
||||
|
||||
return t.writer.Write(line)
|
||||
}
|
||||
|
||||
func (t *defaultLogger) Close() error {
|
||||
// avoid closing stderr
|
||||
if t.internalWriter == os.Stderr {
|
||||
return nil
|
||||
}
|
||||
|
||||
closer, isCloser := t.internalWriter.(io.Closer)
|
||||
if !isCloser {
|
||||
return errors.New("the underlying writer cannot be closed")
|
||||
}
|
||||
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"
|
||||
}
|
||||
|
||||
tz, err := time.LoadLocation(timezoneName)
|
||||
if err != nil {
|
||||
return nil, errors.New("error while setting logging timezone: " + err.Error())
|
||||
}
|
||||
|
||||
return &defaultLogger{
|
||||
writer: wlog.NewWriter(w),
|
||||
internalWriter: w,
|
||||
timezone: tz,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func createStderrLogger(cfg Config) (io.WriteCloser, error) {
|
||||
return newTelegrafWriter(os.Stderr, cfg)
|
||||
}
|
||||
|
||||
func createFileLogger(cfg Config) (io.WriteCloser, error) {
|
||||
if cfg.Logfile == "" {
|
||||
return createStderrLogger(cfg)
|
||||
}
|
||||
|
||||
writer, err := rotate.NewFileWriter(
|
||||
cfg.Logfile,
|
||||
cfg.RotationInterval,
|
||||
cfg.RotationMaxSize,
|
||||
cfg.RotationMaxArchives,
|
||||
)
|
||||
if err != nil {
|
||||
log.Printf("E! Unable to open %s (%s), using stderr", cfg.Logfile, err)
|
||||
return createStderrLogger(cfg)
|
||||
}
|
||||
|
||||
return newTelegrafWriter(writer, cfg)
|
||||
}
|
||||
|
||||
func init() {
|
||||
registerLogger("stderr", createStderrLogger)
|
||||
registerLogger("file", createFileLogger)
|
||||
}
|
||||
|
|
@ -2,15 +2,12 @@ package logger
|
|||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/influxdata/telegraf/config"
|
||||
)
|
||||
|
||||
func TestWriteLogToFile(t *testing.T) {
|
||||
|
|
@ -18,7 +15,7 @@ func TestWriteLogToFile(t *testing.T) {
|
|||
require.NoError(t, err)
|
||||
defer os.Remove(tmpfile.Name())
|
||||
|
||||
cfg := createBasicLogConfig(tmpfile.Name())
|
||||
cfg := createBasicConfig(tmpfile.Name())
|
||||
err = SetupLogging(cfg)
|
||||
require.NoError(t, err)
|
||||
log.Printf("I! TEST")
|
||||
|
|
@ -34,7 +31,7 @@ func TestDebugWriteLogToFile(t *testing.T) {
|
|||
require.NoError(t, err)
|
||||
defer os.Remove(tmpfile.Name())
|
||||
|
||||
cfg := createBasicLogConfig(tmpfile.Name())
|
||||
cfg := createBasicConfig(tmpfile.Name())
|
||||
cfg.Debug = true
|
||||
err = SetupLogging(cfg)
|
||||
require.NoError(t, err)
|
||||
|
|
@ -50,7 +47,7 @@ func TestErrorWriteLogToFile(t *testing.T) {
|
|||
require.NoError(t, err)
|
||||
defer os.Remove(tmpfile.Name())
|
||||
|
||||
cfg := createBasicLogConfig(tmpfile.Name())
|
||||
cfg := createBasicConfig(tmpfile.Name())
|
||||
cfg.Quiet = true
|
||||
err = SetupLogging(cfg)
|
||||
require.NoError(t, err)
|
||||
|
|
@ -67,7 +64,7 @@ func TestAddDefaultLogLevel(t *testing.T) {
|
|||
require.NoError(t, err)
|
||||
defer os.Remove(tmpfile.Name())
|
||||
|
||||
cfg := createBasicLogConfig(tmpfile.Name())
|
||||
cfg := createBasicConfig(tmpfile.Name())
|
||||
cfg.Debug = true
|
||||
err = SetupLogging(cfg)
|
||||
require.NoError(t, err)
|
||||
|
|
@ -83,7 +80,7 @@ func TestWriteToTruncatedFile(t *testing.T) {
|
|||
require.NoError(t, err)
|
||||
defer os.Remove(tmpfile.Name())
|
||||
|
||||
cfg := createBasicLogConfig(tmpfile.Name())
|
||||
cfg := createBasicConfig(tmpfile.Name())
|
||||
cfg.Debug = true
|
||||
err = SetupLogging(cfg)
|
||||
require.NoError(t, err)
|
||||
|
|
@ -106,15 +103,11 @@ func TestWriteToTruncatedFile(t *testing.T) {
|
|||
|
||||
func TestWriteToFileInRotation(t *testing.T) {
|
||||
tempDir := t.TempDir()
|
||||
cfg := createBasicLogConfig(filepath.Join(tempDir, "test.log"))
|
||||
cfg.LogTarget = LogTargetFile
|
||||
cfg.RotationMaxSize = config.Size(30)
|
||||
writer, err := newLogWriter(cfg)
|
||||
require.NoError(t, err)
|
||||
cfg := createBasicConfig(filepath.Join(tempDir, "test.log"))
|
||||
cfg.RotationMaxSize = 30
|
||||
require.NoError(t, SetupLogging(cfg))
|
||||
// Close the writer here, otherwise the temp folder cannot be deleted because the current log file is in use.
|
||||
closer, isCloser := writer.(io.Closer)
|
||||
require.True(t, isCloser)
|
||||
t.Cleanup(func() { require.NoError(t, closer.Close()) })
|
||||
t.Cleanup(func() { require.NoError(t, actualLogger.Close()) })
|
||||
|
||||
log.Printf("I! TEST 1") // Writes 31 bytes, will rotate
|
||||
log.Printf("I! TEST") // Writes 29 byes, no rotation expected
|
||||
|
|
@ -124,23 +117,23 @@ func TestWriteToFileInRotation(t *testing.T) {
|
|||
|
||||
func TestLogTargetSettings(t *testing.T) {
|
||||
actualLogger = nil
|
||||
cfg := LogConfig{
|
||||
cfg := Config{
|
||||
LogTarget: "",
|
||||
Quiet: true,
|
||||
}
|
||||
err := SetupLogging(cfg)
|
||||
require.NoError(t, err)
|
||||
logger, isTelegrafLogger := actualLogger.(*telegrafLog)
|
||||
logger, isTelegrafLogger := actualLogger.(*defaultLogger)
|
||||
require.True(t, isTelegrafLogger)
|
||||
require.Equal(t, logger.internalWriter, os.Stderr)
|
||||
|
||||
cfg = LogConfig{
|
||||
cfg = Config{
|
||||
LogTarget: "stderr",
|
||||
Quiet: true,
|
||||
}
|
||||
err = SetupLogging(cfg)
|
||||
require.NoError(t, err)
|
||||
logger, isTelegrafLogger = actualLogger.(*telegrafLog)
|
||||
logger, isTelegrafLogger = actualLogger.(*defaultLogger)
|
||||
require.True(t, isTelegrafLogger)
|
||||
require.Equal(t, logger.internalWriter, os.Stderr)
|
||||
}
|
||||
|
|
@ -148,7 +141,7 @@ func TestLogTargetSettings(t *testing.T) {
|
|||
func BenchmarkTelegrafLogWrite(b *testing.B) {
|
||||
var msg = []byte("test")
|
||||
var buf bytes.Buffer
|
||||
w, err := newTelegrafWriter(&buf, LogConfig{})
|
||||
w, err := newTelegrafWriter(&buf, Config{})
|
||||
if err != nil {
|
||||
panic("Unable to create log writer.")
|
||||
}
|
||||
|
|
@ -161,10 +154,10 @@ func BenchmarkTelegrafLogWrite(b *testing.B) {
|
|||
}
|
||||
}
|
||||
|
||||
func createBasicLogConfig(filename string) LogConfig {
|
||||
return LogConfig{
|
||||
func createBasicConfig(filename string) Config {
|
||||
return Config{
|
||||
Logfile: filename,
|
||||
LogTarget: LogTargetFile,
|
||||
LogTarget: "file",
|
||||
RotationMaxArchives: -1,
|
||||
}
|
||||
}
|
||||
|
|
@ -12,53 +12,68 @@ import (
|
|||
)
|
||||
|
||||
const (
|
||||
LogTargetEventlog = "eventlog"
|
||||
eidInfo = 1
|
||||
eidWarning = 2
|
||||
eidError = 3
|
||||
eidInfo = 1
|
||||
eidWarning = 2
|
||||
eidError = 3
|
||||
)
|
||||
|
||||
type eventLogger struct {
|
||||
type eventWriter struct {
|
||||
logger *eventlog.Log
|
||||
}
|
||||
|
||||
func (t *eventLogger) Write(b []byte) (int, error) {
|
||||
var err error
|
||||
|
||||
func (w *eventWriter) Write(b []byte) (int, error) {
|
||||
loc := prefixRegex.FindIndex(b)
|
||||
n := len(b)
|
||||
if loc == nil {
|
||||
err = t.logger.Info(1, string(b))
|
||||
} else if n > 2 { //skip empty log messages
|
||||
return n, w.logger.Info(1, string(b))
|
||||
}
|
||||
|
||||
//skip empty log messages
|
||||
if n > 2 {
|
||||
line := strings.Trim(string(b[loc[1]:]), " \t\r\n")
|
||||
switch rune(b[loc[0]]) {
|
||||
case 'I':
|
||||
err = t.logger.Info(eidInfo, line)
|
||||
return n, w.logger.Info(eidInfo, line)
|
||||
case 'W':
|
||||
err = t.logger.Warning(eidWarning, line)
|
||||
return n, w.logger.Warning(eidWarning, line)
|
||||
case 'E':
|
||||
err = t.logger.Error(eidError, line)
|
||||
return n, w.logger.Error(eidError, line)
|
||||
}
|
||||
}
|
||||
|
||||
return n, err
|
||||
return n, nil
|
||||
}
|
||||
|
||||
type eventLoggerCreator struct {
|
||||
logger *eventlog.Log
|
||||
type eventLogger struct {
|
||||
writer io.Writer
|
||||
eventlog *eventlog.Log
|
||||
}
|
||||
|
||||
func (e *eventLoggerCreator) CreateLogger(_ LogConfig) (io.Writer, error) {
|
||||
return wlog.NewWriter(&eventLogger{logger: e.logger}), nil
|
||||
func (e *eventLogger) Write(b []byte) (int, error) {
|
||||
return e.writer.Write(b)
|
||||
}
|
||||
|
||||
func (e *eventLogger) Close() error {
|
||||
return e.eventlog.Close()
|
||||
}
|
||||
|
||||
func createEventLogger(name string) creator {
|
||||
return func(Config) (io.WriteCloser, error) {
|
||||
eventLog, err := eventlog.Open(name)
|
||||
if err != nil {
|
||||
log.Printf("E! An error occurred while initializing an event logger. %s", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
writer := wlog.NewWriter(&eventWriter{logger: eventLog})
|
||||
return &eventLogger{
|
||||
writer: writer,
|
||||
eventlog: eventLog,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func RegisterEventLogger(name string) error {
|
||||
eventLog, err := eventlog.Open(name)
|
||||
if err != nil {
|
||||
log.Printf("E! An error occurred while initializing an event logger. %s", err)
|
||||
return err
|
||||
}
|
||||
|
||||
registerLogger(LogTargetEventlog, &eventLoggerCreator{logger: eventLog})
|
||||
registerLogger("eventlog", createEventLogger(name))
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,7 +12,6 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/sys/windows/svc/eventlog"
|
||||
)
|
||||
|
||||
type Levels int
|
||||
|
|
@ -54,15 +53,13 @@ func TestEventLogIntegration(t *testing.T) {
|
|||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
testPrepareLogger(t)
|
||||
registerLogger("eventlog", createEventLogger("telegraf"))
|
||||
|
||||
config := LogConfig{
|
||||
LogTarget: LogTargetEventlog,
|
||||
config := Config{
|
||||
LogTarget: "eventlog",
|
||||
Logfile: "",
|
||||
}
|
||||
|
||||
err := SetupLogging(config)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, SetupLogging(config))
|
||||
|
||||
now := time.Now()
|
||||
log.Println("I! Info message")
|
||||
|
|
@ -79,15 +76,14 @@ func TestRestrictedEventLogIntegration(t *testing.T) {
|
|||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
testPrepareLogger(t)
|
||||
registerLogger("eventlog", createEventLogger("telegraf"))
|
||||
|
||||
config := LogConfig{
|
||||
LogTarget: LogTargetEventlog,
|
||||
config := Config{
|
||||
LogTarget: "eventlog",
|
||||
Quiet: true,
|
||||
}
|
||||
require.NoError(t, SetupLogging(config))
|
||||
|
||||
err := SetupLogging(config)
|
||||
require.NoError(t, err)
|
||||
//separate previous log messages by small delay
|
||||
time.Sleep(time.Second)
|
||||
now := time.Now()
|
||||
|
|
@ -98,10 +94,3 @@ func TestRestrictedEventLogIntegration(t *testing.T) {
|
|||
require.Len(t, events, 1)
|
||||
require.Contains(t, events, Event{Message: "Error message", Level: Error})
|
||||
}
|
||||
|
||||
func testPrepareLogger(tb testing.TB) {
|
||||
eventLog, err := eventlog.Open("telegraf")
|
||||
require.NoError(tb, err)
|
||||
require.NotNil(tb, eventLog)
|
||||
registerLogger(LogTargetEventlog, &eventLoggerCreator{logger: eventLog})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,96 @@
|
|||
package logger
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/influxdata/telegraf"
|
||||
)
|
||||
|
||||
// Logger defines a logging structure for plugins.
|
||||
type Logger struct {
|
||||
Category string
|
||||
Name string
|
||||
Alias string
|
||||
LogLevel telegraf.LogLevel
|
||||
|
||||
prefix string
|
||||
onError []func()
|
||||
}
|
||||
|
||||
// NewLogger creates a new logger instance
|
||||
func NewLogger(category, name, alias string) telegraf.Logger {
|
||||
var prefix string
|
||||
if category != "" {
|
||||
prefix = "[" + category
|
||||
if name != "" {
|
||||
prefix += "." + name
|
||||
}
|
||||
if alias != "" {
|
||||
prefix += "::" + alias
|
||||
}
|
||||
prefix += "] "
|
||||
}
|
||||
|
||||
return &Logger{
|
||||
Category: category,
|
||||
Name: name,
|
||||
Alias: alias,
|
||||
LogLevel: telegraf.Info,
|
||||
prefix: prefix,
|
||||
}
|
||||
}
|
||||
|
||||
// OnErr defines a callback that triggers only when errors are about to be written to the log
|
||||
func (l *Logger) RegisterErrorCallback(f func()) {
|
||||
l.onError = append(l.onError, f)
|
||||
}
|
||||
|
||||
func (l *Logger) Level() telegraf.LogLevel {
|
||||
return l.LogLevel
|
||||
}
|
||||
|
||||
// Errorf logs an error message, patterned after log.Printf.
|
||||
func (l *Logger) Errorf(format string, args ...interface{}) {
|
||||
log.Printf("E! "+l.prefix+format, args...)
|
||||
for _, f := range l.onError {
|
||||
f()
|
||||
}
|
||||
}
|
||||
|
||||
// Error logs an error message, patterned after log.Print.
|
||||
func (l *Logger) Error(args ...interface{}) {
|
||||
for _, f := range l.onError {
|
||||
f()
|
||||
}
|
||||
log.Print(append([]interface{}{"E! " + l.prefix}, args...)...)
|
||||
}
|
||||
|
||||
// Debugf logs a debug message, patterned after log.Printf.
|
||||
func (l *Logger) Debugf(format string, args ...interface{}) {
|
||||
log.Printf("D! "+l.prefix+" "+format, args...)
|
||||
}
|
||||
|
||||
// Debug logs a debug message, patterned after log.Print.
|
||||
func (l *Logger) Debug(args ...interface{}) {
|
||||
log.Print(append([]interface{}{"D! " + l.prefix}, args...)...)
|
||||
}
|
||||
|
||||
// Warnf logs a warning message, patterned after log.Printf.
|
||||
func (l *Logger) Warnf(format string, args ...interface{}) {
|
||||
log.Printf("W! "+l.prefix+format, args...)
|
||||
}
|
||||
|
||||
// Warn logs a warning message, patterned after log.Print.
|
||||
func (l *Logger) Warn(args ...interface{}) {
|
||||
log.Print(append([]interface{}{"W! " + l.prefix}, args...)...)
|
||||
}
|
||||
|
||||
// Infof logs an information message, patterned after log.Printf.
|
||||
func (l *Logger) Infof(format string, args ...interface{}) {
|
||||
log.Printf("I! "+l.prefix+format, args...)
|
||||
}
|
||||
|
||||
// Info logs an information message, patterned after log.Print.
|
||||
func (l *Logger) Info(args ...interface{}) {
|
||||
log.Print(append([]interface{}{"I! " + l.prefix}, args...)...)
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
package logger
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/influxdata/telegraf/selfstat"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestErrorCounting(t *testing.T) {
|
||||
reg := selfstat.Register(
|
||||
"gather",
|
||||
"errors",
|
||||
map[string]string{"input": "test"},
|
||||
)
|
||||
iLog := Logger{Name: "inputs.test"}
|
||||
iLog.RegisterErrorCallback(func() {
|
||||
reg.Incr(1)
|
||||
})
|
||||
iLog.Error("something went wrong")
|
||||
iLog.Errorf("something went wrong")
|
||||
|
||||
require.Equal(t, int64(2), reg.Get())
|
||||
}
|
||||
185
logger/logger.go
185
logger/logger.go
|
|
@ -1,154 +1,18 @@
|
|||
package logger
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/influxdata/wlog"
|
||||
|
||||
"github.com/influxdata/telegraf/config"
|
||||
"github.com/influxdata/telegraf/internal/rotate"
|
||||
)
|
||||
|
||||
var prefixRegex = regexp.MustCompile("^[DIWE]!")
|
||||
|
||||
const (
|
||||
LogTargetFile = "file"
|
||||
LogTargetStderr = "stderr"
|
||||
)
|
||||
|
||||
// LogConfig contains the log configuration settings
|
||||
type LogConfig struct {
|
||||
// will set the log level to DEBUG
|
||||
Debug bool
|
||||
//will set the log level to ERROR
|
||||
Quiet bool
|
||||
//stderr, stdout, file or eventlog (Windows only)
|
||||
LogTarget string
|
||||
// will direct the logging output to a file. Empty string is
|
||||
// interpreted as stderr. If there is an error opening the file the
|
||||
// logger will fall back to stderr
|
||||
Logfile string
|
||||
// will rotate when current file at the specified time interval
|
||||
RotationInterval config.Duration
|
||||
// will rotate when current file size exceeds this parameter.
|
||||
RotationMaxSize config.Size
|
||||
// maximum rotated files to keep (older ones will be deleted)
|
||||
RotationMaxArchives int
|
||||
// pick a timezone to use when logging. or type 'local' for local time.
|
||||
LogWithTimezone string
|
||||
}
|
||||
|
||||
type creator interface {
|
||||
CreateLogger(cfg LogConfig) (io.Writer, error)
|
||||
}
|
||||
|
||||
var loggerRegistry map[string]creator
|
||||
|
||||
func registerLogger(name string, loggerCreator creator) {
|
||||
if loggerRegistry == nil {
|
||||
loggerRegistry = make(map[string]creator)
|
||||
}
|
||||
loggerRegistry[name] = loggerCreator
|
||||
}
|
||||
|
||||
type telegrafLog struct {
|
||||
writer io.Writer
|
||||
internalWriter io.Writer
|
||||
timezone *time.Location
|
||||
}
|
||||
|
||||
func (t *telegrafLog) Write(b []byte) (n int, err error) {
|
||||
var line []byte
|
||||
timeToPrint := time.Now().In(t.timezone)
|
||||
|
||||
if !prefixRegex.Match(b) {
|
||||
line = append([]byte(timeToPrint.Format(time.RFC3339)+" I! "), b...)
|
||||
} else {
|
||||
line = append([]byte(timeToPrint.Format(time.RFC3339)+" "), b...)
|
||||
}
|
||||
|
||||
return t.writer.Write(line)
|
||||
}
|
||||
|
||||
func (t *telegrafLog) Close() error {
|
||||
stdErrWriter := os.Stderr
|
||||
// avoid closing stderr
|
||||
if t.internalWriter == stdErrWriter {
|
||||
return nil
|
||||
}
|
||||
|
||||
closer, isCloser := t.internalWriter.(io.Closer)
|
||||
if !isCloser {
|
||||
return errors.New("the underlying writer cannot be closed")
|
||||
}
|
||||
return closer.Close()
|
||||
}
|
||||
|
||||
// newTelegrafWriter returns a logging-wrapped writer.
|
||||
func newTelegrafWriter(w io.Writer, c LogConfig) (io.Writer, error) {
|
||||
timezoneName := c.LogWithTimezone
|
||||
if strings.EqualFold(timezoneName, "local") {
|
||||
timezoneName = "Local"
|
||||
}
|
||||
|
||||
tz, err := time.LoadLocation(timezoneName)
|
||||
if err != nil {
|
||||
return nil, errors.New("error while setting logging timezone: " + err.Error())
|
||||
}
|
||||
|
||||
return &telegrafLog{
|
||||
writer: wlog.NewWriter(w),
|
||||
internalWriter: w,
|
||||
timezone: tz,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// SetupLogging configures the logging output.
|
||||
func SetupLogging(cfg LogConfig) error {
|
||||
_, err := newLogWriter(cfg)
|
||||
return err
|
||||
}
|
||||
|
||||
type telegrafLogCreator struct {
|
||||
}
|
||||
|
||||
func (t *telegrafLogCreator) CreateLogger(cfg LogConfig) (io.Writer, error) {
|
||||
var writer, defaultWriter io.Writer
|
||||
defaultWriter = os.Stderr
|
||||
|
||||
switch cfg.LogTarget {
|
||||
case LogTargetFile:
|
||||
if cfg.Logfile != "" {
|
||||
var err error
|
||||
if writer, err =
|
||||
rotate.NewFileWriter(cfg.Logfile, time.Duration(cfg.RotationInterval), int64(cfg.RotationMaxSize), cfg.RotationMaxArchives); err != nil {
|
||||
log.Printf("E! Unable to open %s (%s), using stderr", cfg.Logfile, err)
|
||||
writer = defaultWriter
|
||||
}
|
||||
} else {
|
||||
writer = defaultWriter
|
||||
}
|
||||
case LogTargetStderr, "":
|
||||
writer = defaultWriter
|
||||
default:
|
||||
log.Printf("E! Unsupported logtarget: %s, using stderr", cfg.LogTarget)
|
||||
writer = defaultWriter
|
||||
}
|
||||
|
||||
return newTelegrafWriter(writer, cfg)
|
||||
}
|
||||
|
||||
// Keep track what is actually set as a log output, because log package doesn't provide a getter.
|
||||
// It allows closing previous writer if re-set and have possibility to test what is actually set
|
||||
var actualLogger io.Writer
|
||||
var actualLogger io.WriteCloser
|
||||
|
||||
func newLogWriter(cfg LogConfig) (io.Writer, error) {
|
||||
// SetupLogging configures the logging output.
|
||||
func SetupLogging(cfg Config) error {
|
||||
log.SetFlags(0)
|
||||
if cfg.Debug {
|
||||
wlog.SetLevel(wlog.DEBUG)
|
||||
|
|
@ -159,29 +23,40 @@ func newLogWriter(cfg LogConfig) (io.Writer, error) {
|
|||
if !cfg.Debug && !cfg.Quiet {
|
||||
wlog.SetLevel(wlog.INFO)
|
||||
}
|
||||
var logWriter io.Writer
|
||||
if logCreator, ok := loggerRegistry[cfg.LogTarget]; ok {
|
||||
logWriter, _ = logCreator.CreateLogger(cfg)
|
||||
}
|
||||
if logWriter == nil {
|
||||
logWriter, _ = (&telegrafLogCreator{}).CreateLogger(cfg)
|
||||
|
||||
if cfg.LogTarget == "" {
|
||||
cfg.LogTarget = "stderr"
|
||||
}
|
||||
|
||||
if closer, isCloser := actualLogger.(io.Closer); isCloser {
|
||||
if err := closer.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Get the logging factory
|
||||
logCreator, ok := loggerRegistry[cfg.LogTarget]
|
||||
if !ok {
|
||||
log.Printf("E! Unsupported logtarget: %s, using stderr", cfg.LogTarget)
|
||||
logCreator = createStderrLogger
|
||||
}
|
||||
|
||||
// Create the root logging instance
|
||||
logWriter, err := logCreator(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Close the previous logger if possible
|
||||
if err := CloseLogging(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Use the new logger and store a reference
|
||||
log.SetOutput(logWriter)
|
||||
actualLogger = logWriter
|
||||
|
||||
return logWriter, nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
tlc := &telegrafLogCreator{}
|
||||
registerLogger("", tlc)
|
||||
registerLogger(LogTargetStderr, tlc)
|
||||
registerLogger(LogTargetFile, tlc)
|
||||
func CloseLogging() error {
|
||||
if actualLogger == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return actualLogger.Close()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,14 @@
|
|||
package logger
|
||||
|
||||
import "io"
|
||||
|
||||
type creator func(cfg Config) (io.WriteCloser, error)
|
||||
|
||||
var loggerRegistry map[string]creator
|
||||
|
||||
func registerLogger(name string, loggerCreator creator) {
|
||||
if loggerRegistry == nil {
|
||||
loggerRegistry = make(map[string]creator)
|
||||
}
|
||||
loggerRegistry[name] = loggerCreator
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
package models
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
|
||||
"github.com/influxdata/telegraf"
|
||||
)
|
||||
|
||||
// logName returns the log-friendly name/type.
|
||||
func logName(pluginType, name, alias string) string {
|
||||
if alias == "" {
|
||||
return pluginType + "." + name
|
||||
}
|
||||
return pluginType + "." + name + "::" + alias
|
||||
}
|
||||
|
||||
func SetLoggerOnPlugin(i interface{}, logger telegraf.Logger) {
|
||||
valI := reflect.ValueOf(i)
|
||||
|
||||
if valI.Type().Kind() != reflect.Ptr {
|
||||
valI = reflect.New(reflect.TypeOf(i))
|
||||
}
|
||||
|
||||
field := valI.Elem().FieldByName("Log")
|
||||
if !field.IsValid() {
|
||||
return
|
||||
}
|
||||
|
||||
switch field.Type().String() {
|
||||
case "telegraf.Logger":
|
||||
if field.CanSet() {
|
||||
field.Set(reflect.ValueOf(logger))
|
||||
}
|
||||
default:
|
||||
logger.Debugf("Plugin %q defines a 'Log' field on its struct of an unexpected type %q. Expected telegraf.Logger",
|
||||
valI.Type().Name(), field.Type().String())
|
||||
}
|
||||
}
|
||||
148
models/log.go
148
models/log.go
|
|
@ -1,148 +0,0 @@
|
|||
package models
|
||||
|
||||
import (
|
||||
"log"
|
||||
"reflect"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/influxdata/telegraf"
|
||||
)
|
||||
|
||||
// Logger defines a logging structure for plugins.
|
||||
type Logger struct {
|
||||
OnErrs []func()
|
||||
Name string // Name is the plugin name, will be printed in the `[]`.
|
||||
}
|
||||
|
||||
// NewLogger creates a new logger instance
|
||||
func NewLogger(pluginType, name, alias string) *Logger {
|
||||
return &Logger{
|
||||
Name: logName(pluginType, name, alias),
|
||||
}
|
||||
}
|
||||
|
||||
// OnErr defines a callback that triggers only when errors are about to be written to the log
|
||||
func (l *Logger) OnErr(f func()) {
|
||||
l.OnErrs = append(l.OnErrs, f)
|
||||
}
|
||||
|
||||
// Errorf logs an error message, patterned after log.Printf.
|
||||
func (l *Logger) Errorf(format string, args ...interface{}) {
|
||||
for _, f := range l.OnErrs {
|
||||
f()
|
||||
}
|
||||
log.Printf("E! ["+l.Name+"] "+format, args...)
|
||||
}
|
||||
|
||||
// Error logs an error message, patterned after log.Print.
|
||||
func (l *Logger) Error(args ...interface{}) {
|
||||
for _, f := range l.OnErrs {
|
||||
f()
|
||||
}
|
||||
log.Print(append([]interface{}{"E! [" + l.Name + "] "}, args...)...)
|
||||
}
|
||||
|
||||
// Debugf logs a debug message, patterned after log.Printf.
|
||||
func (l *Logger) Debugf(format string, args ...interface{}) {
|
||||
log.Printf("D! ["+l.Name+"] "+format, args...)
|
||||
}
|
||||
|
||||
// Debug logs a debug message, patterned after log.Print.
|
||||
func (l *Logger) Debug(args ...interface{}) {
|
||||
log.Print(append([]interface{}{"D! [" + l.Name + "] "}, args...)...)
|
||||
}
|
||||
|
||||
// Warnf logs a warning message, patterned after log.Printf.
|
||||
func (l *Logger) Warnf(format string, args ...interface{}) {
|
||||
log.Printf("W! ["+l.Name+"] "+format, args...)
|
||||
}
|
||||
|
||||
// Warn logs a warning message, patterned after log.Print.
|
||||
func (l *Logger) Warn(args ...interface{}) {
|
||||
log.Print(append([]interface{}{"W! [" + l.Name + "] "}, args...)...)
|
||||
}
|
||||
|
||||
// Infof logs an information message, patterned after log.Printf.
|
||||
func (l *Logger) Infof(format string, args ...interface{}) {
|
||||
log.Printf("I! ["+l.Name+"] "+format, args...)
|
||||
}
|
||||
|
||||
// Info logs an information message, patterned after log.Print.
|
||||
func (l *Logger) Info(args ...interface{}) {
|
||||
log.Print(append([]interface{}{"I! [" + l.Name + "] "}, args...)...)
|
||||
}
|
||||
|
||||
// logName returns the log-friendly name/type.
|
||||
func logName(pluginType, name, alias string) string {
|
||||
if alias == "" {
|
||||
return pluginType + "." + name
|
||||
}
|
||||
return pluginType + "." + name + "::" + alias
|
||||
}
|
||||
|
||||
func SetLoggerOnPlugin(i interface{}, logger telegraf.Logger) {
|
||||
valI := reflect.ValueOf(i)
|
||||
|
||||
if valI.Type().Kind() != reflect.Ptr {
|
||||
valI = reflect.New(reflect.TypeOf(i))
|
||||
}
|
||||
|
||||
field := valI.Elem().FieldByName("Log")
|
||||
if !field.IsValid() {
|
||||
return
|
||||
}
|
||||
|
||||
switch field.Type().String() {
|
||||
case "telegraf.Logger":
|
||||
if field.CanSet() {
|
||||
field.Set(reflect.ValueOf(logger))
|
||||
}
|
||||
default:
|
||||
logger.Debugf("Plugin %q defines a 'Log' field on its struct of an unexpected type %q. Expected telegraf.Logger",
|
||||
valI.Type().Name(), field.Type().String())
|
||||
}
|
||||
}
|
||||
|
||||
func deprecationPrefix(level telegraf.Escalation) string {
|
||||
switch level {
|
||||
case telegraf.Warn:
|
||||
return "W! " + color.YellowString("DeprecationWarning")
|
||||
case telegraf.Error:
|
||||
return "E! " + color.RedString("DeprecationError")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func PrintPluginDeprecationNotice(level telegraf.Escalation, name string, info telegraf.DeprecationInfo) {
|
||||
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,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func PrintOptionDeprecationNotice(level telegraf.Escalation, plugin, option string, info telegraf.DeprecationInfo) {
|
||||
switch level {
|
||||
case telegraf.Warn, telegraf.Error:
|
||||
prefix := deprecationPrefix(level)
|
||||
log.Printf(
|
||||
"%s: Option %q of plugin %q deprecated since version %s and will be removed in %s: %s",
|
||||
prefix, option, plugin, info.Since, info.RemovalIn, info.Notice,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func PrintOptionValueDeprecationNotice(level telegraf.Escalation, plugin, option string, value interface{}, info telegraf.DeprecationInfo) {
|
||||
switch level {
|
||||
case telegraf.Warn, telegraf.Error:
|
||||
prefix := deprecationPrefix(level)
|
||||
log.Printf(
|
||||
`%s: Value "%+v" for option %q of plugin %q deprecated since version %s and will be removed in %s: %s`,
|
||||
prefix, value, option, plugin, info.Since, info.RemovalIn, info.Notice,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/influxdata/telegraf"
|
||||
logging "github.com/influxdata/telegraf/logger"
|
||||
"github.com/influxdata/telegraf/metric"
|
||||
"github.com/influxdata/telegraf/selfstat"
|
||||
)
|
||||
|
|
@ -30,8 +31,8 @@ func NewRunningAggregator(aggregator telegraf.Aggregator, config *AggregatorConf
|
|||
}
|
||||
|
||||
aggErrorsRegister := selfstat.Register("aggregate", "errors", tags)
|
||||
logger := NewLogger("aggregators", config.Name, config.Alias)
|
||||
logger.OnErr(func() {
|
||||
logger := logging.NewLogger("aggregators", config.Name, config.Alias)
|
||||
logger.RegisterErrorCallback(func() {
|
||||
aggErrorsRegister.Incr(1)
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import (
|
|||
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/internal"
|
||||
logging "github.com/influxdata/telegraf/logger"
|
||||
"github.com/influxdata/telegraf/selfstat"
|
||||
)
|
||||
|
||||
|
|
@ -40,8 +41,8 @@ func NewRunningInput(input telegraf.Input, config *InputConfig) *RunningInput {
|
|||
}
|
||||
|
||||
inputErrorsRegister := selfstat.Register("gather", "errors", tags)
|
||||
logger := NewLogger("inputs", config.Name, config.Alias)
|
||||
logger.OnErr(func() {
|
||||
logger := logging.NewLogger("inputs", config.Name, config.Alias)
|
||||
logger.RegisterErrorCallback(func() {
|
||||
inputErrorsRegister.Incr(1)
|
||||
GlobalGatherErrors.Incr(1)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import (
|
|||
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/internal"
|
||||
logging "github.com/influxdata/telegraf/logger"
|
||||
"github.com/influxdata/telegraf/selfstat"
|
||||
)
|
||||
|
||||
|
|
@ -76,8 +77,8 @@ func NewRunningOutput(
|
|||
}
|
||||
|
||||
writeErrorsRegister := selfstat.Register("write", "errors", tags)
|
||||
logger := NewLogger("outputs", config.Name, config.Alias)
|
||||
logger.OnErr(func() {
|
||||
logger := logging.NewLogger("outputs", config.Name, config.Alias)
|
||||
logger.RegisterErrorCallback(func() {
|
||||
writeErrorsRegister.Incr(1)
|
||||
})
|
||||
SetLoggerOnPlugin(output, logger)
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/influxdata/telegraf"
|
||||
logging "github.com/influxdata/telegraf/logger"
|
||||
"github.com/influxdata/telegraf/selfstat"
|
||||
)
|
||||
|
||||
|
|
@ -23,8 +24,8 @@ func NewRunningParser(parser telegraf.Parser, config *ParserConfig) *RunningPars
|
|||
}
|
||||
|
||||
parserErrorsRegister := selfstat.Register("parser", "errors", tags)
|
||||
logger := NewLogger("parsers", config.DataFormat+"::"+config.Parent, config.Alias)
|
||||
logger.OnErr(func() {
|
||||
logger := logging.NewLogger("parsers", config.DataFormat+"::"+config.Parent, config.Alias)
|
||||
logger.RegisterErrorCallback(func() {
|
||||
parserErrorsRegister.Incr(1)
|
||||
})
|
||||
SetLoggerOnPlugin(parser, logger)
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"sync"
|
||||
|
||||
"github.com/influxdata/telegraf"
|
||||
logging "github.com/influxdata/telegraf/logger"
|
||||
"github.com/influxdata/telegraf/selfstat"
|
||||
)
|
||||
|
||||
|
|
@ -36,8 +37,8 @@ func NewRunningProcessor(processor telegraf.StreamingProcessor, config *Processo
|
|||
}
|
||||
|
||||
processErrorsRegister := selfstat.Register("process", "errors", tags)
|
||||
logger := NewLogger("processors", config.Name, config.Alias)
|
||||
logger.OnErr(func() {
|
||||
logger := logging.NewLogger("processors", config.Name, config.Alias)
|
||||
logger.RegisterErrorCallback(func() {
|
||||
processErrorsRegister.Incr(1)
|
||||
})
|
||||
SetLoggerOnPlugin(processor, logger)
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/influxdata/telegraf"
|
||||
logging "github.com/influxdata/telegraf/logger"
|
||||
"github.com/influxdata/telegraf/plugins/serializers"
|
||||
"github.com/influxdata/telegraf/selfstat"
|
||||
)
|
||||
|
|
@ -33,8 +34,8 @@ func NewRunningSerializer(serializer serializers.Serializer, config *SerializerC
|
|||
}
|
||||
|
||||
serializerErrorsRegister := selfstat.Register("serializer", "errors", tags)
|
||||
logger := NewLogger("serializers", config.DataFormat+"::"+config.Parent, config.Alias)
|
||||
logger.OnErr(func() {
|
||||
logger := logging.NewLogger("serializers", config.DataFormat+"::"+config.Parent, config.Alias)
|
||||
logger.RegisterErrorCallback(func() {
|
||||
serializerErrorsRegister.Incr(1)
|
||||
})
|
||||
SetLoggerOnPlugin(serializer, logger)
|
||||
|
|
|
|||
44
plugin.go
44
plugin.go
|
|
@ -1,29 +1,5 @@
|
|||
package telegraf
|
||||
|
||||
var Debug bool
|
||||
|
||||
// Escalation level for the plugin or option
|
||||
type Escalation int
|
||||
|
||||
func (e Escalation) String() string {
|
||||
switch e {
|
||||
case Warn:
|
||||
return "WARN"
|
||||
case Error:
|
||||
return "ERROR"
|
||||
}
|
||||
return "NONE"
|
||||
}
|
||||
|
||||
const (
|
||||
// None means no deprecation
|
||||
None Escalation = iota
|
||||
// Warn means deprecated but still within the grace period
|
||||
Warn
|
||||
// Error means deprecated and beyond grace period
|
||||
Error
|
||||
)
|
||||
|
||||
// DeprecationInfo contains information for marking a plugin deprecated.
|
||||
type DeprecationInfo struct {
|
||||
// Since specifies the version since when the plugin is deprecated
|
||||
|
|
@ -80,23 +56,3 @@ type StatefulPlugin interface {
|
|||
// initialization (after Init() function).
|
||||
SetState(state interface{}) error
|
||||
}
|
||||
|
||||
// Logger defines an plugin-related interface for logging.
|
||||
type Logger interface {
|
||||
// Errorf logs an error message, patterned after log.Printf.
|
||||
Errorf(format string, args ...interface{})
|
||||
// Error logs an error message, patterned after log.Print.
|
||||
Error(args ...interface{})
|
||||
// Debugf logs a debug message, patterned after log.Printf.
|
||||
Debugf(format string, args ...interface{})
|
||||
// Debug logs a debug message, patterned after log.Print.
|
||||
Debug(args ...interface{})
|
||||
// Warnf logs a warning message, patterned after log.Printf.
|
||||
Warnf(format string, args ...interface{})
|
||||
// Warn logs a warning message, patterned after log.Print.
|
||||
Warn(args ...interface{})
|
||||
// Infof logs an information message, patterned after log.Printf.
|
||||
Infof(format string, args ...interface{})
|
||||
// Info logs an information message, patterned after log.Print.
|
||||
Info(args ...interface{})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import (
|
|||
"github.com/IBM/sarama"
|
||||
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/models"
|
||||
"github.com/influxdata/telegraf/logger"
|
||||
)
|
||||
|
||||
type Logger struct {
|
||||
|
|
@ -29,6 +29,5 @@ func (l *DebugLogger) Println(v ...interface{}) {
|
|||
|
||||
// SetLogger configures a debug logger for kafka (sarama)
|
||||
func (k *Logger) SetLogger() {
|
||||
log := &models.Logger{Name: "sarama"}
|
||||
sarama.Logger = &DebugLogger{Log: log}
|
||||
sarama.Logger = &DebugLogger{Log: logger.NewLogger("sarama", "", "")}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/logger"
|
||||
"github.com/influxdata/telegraf/plugins/serializers/influx"
|
||||
)
|
||||
|
||||
|
|
@ -38,7 +39,7 @@ type Shim struct {
|
|||
Processor telegraf.StreamingProcessor
|
||||
Output telegraf.Output
|
||||
|
||||
log *Logger
|
||||
log telegraf.Logger
|
||||
|
||||
// streams
|
||||
stdin io.Reader
|
||||
|
|
@ -59,7 +60,7 @@ func New() *Shim {
|
|||
stdin: os.Stdin,
|
||||
stdout: os.Stdout,
|
||||
stderr: os.Stderr,
|
||||
log: NewLogger(),
|
||||
log: logger.NewLogger("", "", ""),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -9,11 +9,12 @@ import (
|
|||
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/agent"
|
||||
"github.com/influxdata/telegraf/models"
|
||||
)
|
||||
|
||||
// AddInput adds the input to the shim. Later calls to Run() will run this input.
|
||||
func (s *Shim) AddInput(input telegraf.Input) error {
|
||||
setLoggerOnPlugin(input, s.Log())
|
||||
models.SetLoggerOnPlugin(input, s.Log())
|
||||
if p, ok := input.(telegraf.Initializer); ok {
|
||||
err := p.Init()
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -1,86 +0,0 @@
|
|||
package shim
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log" //nolint:depguard // Allow exceptional but valid use of log here.
|
||||
"os"
|
||||
"reflect"
|
||||
|
||||
"github.com/influxdata/telegraf"
|
||||
)
|
||||
|
||||
func init() {
|
||||
log.SetOutput(os.Stderr)
|
||||
}
|
||||
|
||||
// Logger defines a logging structure for plugins.
|
||||
// external plugins can only ever write to stderr and writing to stdout
|
||||
// would interfere with input/processor writing out of metrics.
|
||||
type Logger struct{}
|
||||
|
||||
// NewLogger creates a new logger instance
|
||||
func NewLogger() *Logger {
|
||||
return &Logger{}
|
||||
}
|
||||
|
||||
// Errorf logs an error message, patterned after log.Printf.
|
||||
func (l *Logger) Errorf(format string, args ...interface{}) {
|
||||
log.Printf("E! "+format, args...)
|
||||
}
|
||||
|
||||
// Error logs an error message, patterned after log.Print.
|
||||
func (l *Logger) Error(args ...interface{}) {
|
||||
log.Print("E! ", fmt.Sprint(args...))
|
||||
}
|
||||
|
||||
// Debugf logs a debug message, patterned after log.Printf.
|
||||
func (l *Logger) Debugf(format string, args ...interface{}) {
|
||||
log.Printf("D! "+format, args...)
|
||||
}
|
||||
|
||||
// Debug logs a debug message, patterned after log.Print.
|
||||
func (l *Logger) Debug(args ...interface{}) {
|
||||
log.Print("D! ", fmt.Sprint(args...))
|
||||
}
|
||||
|
||||
// Warnf logs a warning message, patterned after log.Printf.
|
||||
func (l *Logger) Warnf(format string, args ...interface{}) {
|
||||
log.Printf("W! "+format, args...)
|
||||
}
|
||||
|
||||
// Warn logs a warning message, patterned after log.Print.
|
||||
func (l *Logger) Warn(args ...interface{}) {
|
||||
log.Print("W! ", fmt.Sprint(args...))
|
||||
}
|
||||
|
||||
// Infof logs an information message, patterned after log.Printf.
|
||||
func (l *Logger) Infof(format string, args ...interface{}) {
|
||||
log.Printf("I! "+format, args...)
|
||||
}
|
||||
|
||||
// Info logs an information message, patterned after log.Print.
|
||||
func (l *Logger) Info(args ...interface{}) {
|
||||
log.Print("I! ", fmt.Sprint(args...))
|
||||
}
|
||||
|
||||
// setLoggerOnPlugin injects the logger into the plugin,
|
||||
// if it defines Log telegraf.Logger. This is sort of like SetLogger but using
|
||||
// reflection instead of forcing the plugin author to define the function for it
|
||||
func setLoggerOnPlugin(i interface{}, logger telegraf.Logger) {
|
||||
valI := reflect.ValueOf(i)
|
||||
|
||||
if valI.Type().Kind() != reflect.Ptr {
|
||||
valI = reflect.New(reflect.TypeOf(i))
|
||||
}
|
||||
|
||||
field := valI.Elem().FieldByName("Log")
|
||||
if !field.IsValid() {
|
||||
return
|
||||
}
|
||||
|
||||
if field.Type().String() == "telegraf.Logger" {
|
||||
if field.CanSet() {
|
||||
field.Set(reflect.ValueOf(logger))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -5,12 +5,13 @@ import (
|
|||
"fmt"
|
||||
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/models"
|
||||
"github.com/influxdata/telegraf/plugins/parsers/influx"
|
||||
)
|
||||
|
||||
// AddOutput adds the input to the shim. Later calls to Run() will run this.
|
||||
func (s *Shim) AddOutput(output telegraf.Output) error {
|
||||
setLoggerOnPlugin(output, s.Log())
|
||||
models.SetLoggerOnPlugin(output, s.Log())
|
||||
if p, ok := output.(telegraf.Initializer); ok {
|
||||
err := p.Init()
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -8,20 +8,21 @@ import (
|
|||
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/agent"
|
||||
"github.com/influxdata/telegraf/models"
|
||||
"github.com/influxdata/telegraf/plugins/parsers/influx"
|
||||
"github.com/influxdata/telegraf/plugins/processors"
|
||||
)
|
||||
|
||||
// AddProcessor adds the processor to the shim. Later calls to Run() will run this.
|
||||
func (s *Shim) AddProcessor(processor telegraf.Processor) error {
|
||||
setLoggerOnPlugin(processor, s.Log())
|
||||
models.SetLoggerOnPlugin(processor, s.Log())
|
||||
p := processors.NewStreamingProcessorFromProcessor(processor)
|
||||
return s.AddStreamingProcessor(p)
|
||||
}
|
||||
|
||||
// AddStreamingProcessor adds the processor to the shim. Later calls to Run() will run this.
|
||||
func (s *Shim) AddStreamingProcessor(processor telegraf.StreamingProcessor) error {
|
||||
setLoggerOnPlugin(processor, s.Log())
|
||||
models.SetLoggerOnPlugin(processor, s.Log())
|
||||
if p, ok := processor.(telegraf.Initializer); ok {
|
||||
err := p.Init()
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ import (
|
|||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/agent"
|
||||
"github.com/influxdata/telegraf/config"
|
||||
"github.com/influxdata/telegraf/logger"
|
||||
"github.com/influxdata/telegraf/models"
|
||||
"github.com/influxdata/telegraf/plugins/parsers/influx"
|
||||
"github.com/influxdata/telegraf/testutil"
|
||||
|
|
@ -230,7 +231,7 @@ func (tm *testMetricMaker) MakeMetric(metric telegraf.Metric) telegraf.Metric {
|
|||
}
|
||||
|
||||
func (tm *testMetricMaker) Log() telegraf.Logger {
|
||||
return models.NewLogger("test", "test", "")
|
||||
return logger.NewLogger("test", "test", "")
|
||||
}
|
||||
|
||||
type testOutput struct {
|
||||
|
|
|
|||
|
|
@ -54,7 +54,9 @@ type Runner interface {
|
|||
Run(string, []string, time.Duration) ([]byte, []byte, error)
|
||||
}
|
||||
|
||||
type CommandRunner struct{}
|
||||
type CommandRunner struct {
|
||||
debug bool
|
||||
}
|
||||
|
||||
func (c CommandRunner) truncate(buf bytes.Buffer) bytes.Buffer {
|
||||
// Limit the number of bytes.
|
||||
|
|
|
|||
|
|
@ -10,7 +10,6 @@ import (
|
|||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/internal"
|
||||
"github.com/kballard/go-shellquote"
|
||||
)
|
||||
|
|
@ -42,7 +41,7 @@ func (c CommandRunner) Run(
|
|||
runErr := internal.RunTimeout(cmd, timeout)
|
||||
|
||||
out = removeWindowsCarriageReturns(out)
|
||||
if stderr.Len() > 0 && !telegraf.Debug {
|
||||
if stderr.Len() > 0 && !c.debug {
|
||||
stderr = removeWindowsCarriageReturns(stderr)
|
||||
stderr = c.truncate(stderr)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,7 +10,6 @@ import (
|
|||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/internal"
|
||||
"github.com/kballard/go-shellquote"
|
||||
)
|
||||
|
|
@ -44,7 +43,7 @@ func (c CommandRunner) Run(
|
|||
runErr := internal.RunTimeout(cmd, timeout)
|
||||
|
||||
out = removeWindowsCarriageReturns(out)
|
||||
if stderr.Len() > 0 && !telegraf.Debug {
|
||||
if stderr.Len() > 0 && !c.debug {
|
||||
stderr = removeWindowsCarriageReturns(stderr)
|
||||
stderr = c.truncate(stderr)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import (
|
|||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/agent"
|
||||
"github.com/influxdata/telegraf/config"
|
||||
"github.com/influxdata/telegraf/logger"
|
||||
"github.com/influxdata/telegraf/metric"
|
||||
"github.com/influxdata/telegraf/models"
|
||||
"github.com/influxdata/telegraf/plugins/parsers/influx"
|
||||
|
|
@ -185,7 +186,7 @@ func (tm *TestMetricMaker) MakeMetric(aMetric telegraf.Metric) telegraf.Metric {
|
|||
}
|
||||
|
||||
func (tm *TestMetricMaker) Log() telegraf.Logger {
|
||||
return models.NewLogger("TestPlugin", "test", "")
|
||||
return logger.NewLogger("TestPlugin", "test", "")
|
||||
}
|
||||
|
||||
var counter = flag.Bool("counter", false,
|
||||
|
|
|
|||
|
|
@ -18,7 +18,6 @@ import (
|
|||
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/config"
|
||||
"github.com/influxdata/telegraf/models"
|
||||
"github.com/influxdata/telegraf/plugins/inputs"
|
||||
)
|
||||
|
||||
|
|
@ -239,7 +238,7 @@ func (p *PowerStat) parsePackageMetrics() error {
|
|||
// Also, it warns if deprecated metric has been set.
|
||||
func (p *PowerStat) parseCPUMetrics() error {
|
||||
if slices.Contains(p.CPUMetrics, cpuBusyCycles) {
|
||||
models.PrintOptionValueDeprecationNotice(telegraf.Warn, "inputs.intel_powerstat", "cpu_metrics", cpuBusyCycles, telegraf.DeprecationInfo{
|
||||
config.PrintOptionValueDeprecationNotice("inputs.intel_powerstat", "cpu_metrics", cpuBusyCycles, telegraf.DeprecationInfo{
|
||||
Since: "1.23.0",
|
||||
RemovalIn: "2.0.0",
|
||||
Notice: "'cpu_c0_state_residency' metric name should be used instead.",
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import (
|
|||
"fmt"
|
||||
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/models"
|
||||
"github.com/influxdata/telegraf/config"
|
||||
)
|
||||
|
||||
//go:embed sample_register.conf
|
||||
|
|
@ -269,7 +269,7 @@ func (c *ConfigurationOriginal) validateFieldDefinitions(fieldDefs []fieldDefini
|
|||
|
||||
func (c *ConfigurationOriginal) normalizeInputDatatype(dataType string, words int) (string, error) {
|
||||
if dataType == "FLOAT32" {
|
||||
models.PrintOptionValueDeprecationNotice(telegraf.Warn, "input.modbus", "data_type", "FLOAT32", telegraf.DeprecationInfo{
|
||||
config.PrintOptionValueDeprecationNotice("input.modbus", "data_type", "FLOAT32", telegraf.DeprecationInfo{
|
||||
Since: "v1.16.0",
|
||||
RemovalIn: "v2.0.0",
|
||||
Notice: "Use 'UFIXED' instead",
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import (
|
|||
"math"
|
||||
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/models"
|
||||
"github.com/influxdata/telegraf/config"
|
||||
)
|
||||
|
||||
//go:embed sample_request.conf
|
||||
|
|
@ -79,8 +79,7 @@ func (c *ConfigurationPerRequest) Check() error {
|
|||
switch def.Optimization {
|
||||
case "", "none", "shrink", "rearrange":
|
||||
case "aggressive":
|
||||
models.PrintOptionValueDeprecationNotice(
|
||||
telegraf.Warn,
|
||||
config.PrintOptionValueDeprecationNotice(
|
||||
"inputs.modbus",
|
||||
"optimization",
|
||||
"aggressive",
|
||||
|
|
|
|||
|
|
@ -2248,7 +2248,6 @@ func TestRequestEmptyFields(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestRequestMultipleSlavesOneFail(t *testing.T) {
|
||||
telegraf.Debug = true
|
||||
modbus := Modbus{
|
||||
Name: "Test",
|
||||
Controller: "tcp://localhost:1502",
|
||||
|
|
|
|||
|
|
@ -22,11 +22,6 @@ import (
|
|||
"github.com/influxdata/telegraf/testutil"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
telegraf.Debug = false
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func TestControllers(t *testing.T) {
|
||||
var tests = []struct {
|
||||
name string
|
||||
|
|
@ -139,7 +134,7 @@ func TestControllers(t *testing.T) {
|
|||
Name: "dummy",
|
||||
Controller: tt.controller,
|
||||
TransmissionMode: tt.mode,
|
||||
Log: testutil.Logger{},
|
||||
Log: testutil.Logger{Quiet: true},
|
||||
}
|
||||
err := plugin.Init()
|
||||
if tt.errmsg != "" {
|
||||
|
|
@ -180,7 +175,7 @@ func TestRetrySuccessful(t *testing.T) {
|
|||
Name: "TestRetry",
|
||||
Controller: "tcp://localhost:1502",
|
||||
Retries: maxretries,
|
||||
Log: testutil.Logger{},
|
||||
Log: testutil.Logger{Quiet: true},
|
||||
}
|
||||
modbus.SlaveID = 1
|
||||
modbus.Coils = []fieldDefinition{
|
||||
|
|
@ -233,7 +228,7 @@ func TestRetryFailExhausted(t *testing.T) {
|
|||
Name: "TestRetryFailExhausted",
|
||||
Controller: "tcp://localhost:1502",
|
||||
Retries: maxretries,
|
||||
Log: testutil.Logger{},
|
||||
Log: testutil.Logger{Quiet: true},
|
||||
}
|
||||
modbus.SlaveID = 1
|
||||
modbus.Coils = []fieldDefinition{
|
||||
|
|
@ -276,7 +271,7 @@ func TestRetryFailIllegal(t *testing.T) {
|
|||
Name: "TestRetryFailExhausted",
|
||||
Controller: "tcp://localhost:1502",
|
||||
Retries: maxretries,
|
||||
Log: testutil.Logger{},
|
||||
Log: testutil.Logger{Quiet: true},
|
||||
}
|
||||
modbus.SlaveID = 1
|
||||
modbus.Coils = []fieldDefinition{
|
||||
|
|
@ -495,7 +490,7 @@ func TestRegisterWorkaroundsOneRequestPerField(t *testing.T) {
|
|||
Name: "Test",
|
||||
Controller: "tcp://localhost:1502",
|
||||
ConfigurationType: "register",
|
||||
Log: testutil.Logger{},
|
||||
Log: testutil.Logger{Quiet: true},
|
||||
Workarounds: ModbusWorkarounds{OnRequestPerField: true},
|
||||
}
|
||||
plugin.SlaveID = 1
|
||||
|
|
@ -545,7 +540,7 @@ func TestRequestsWorkaroundsReadCoilsStartingAtZeroRegister(t *testing.T) {
|
|||
Name: "Test",
|
||||
Controller: "tcp://localhost:1502",
|
||||
ConfigurationType: "register",
|
||||
Log: testutil.Logger{},
|
||||
Log: testutil.Logger{Quiet: true},
|
||||
Workarounds: ModbusWorkarounds{ReadCoilsStartingAtZero: true},
|
||||
}
|
||||
plugin.SlaveID = 1
|
||||
|
|
@ -692,7 +687,7 @@ func TestWorkaroundsStringRegisterLocation(t *testing.T) {
|
|||
Name: "Test",
|
||||
Controller: "tcp://localhost:1502",
|
||||
ConfigurationType: "request",
|
||||
Log: testutil.Logger{},
|
||||
Log: testutil.Logger{Quiet: true},
|
||||
Workarounds: ModbusWorkarounds{StringRegisterLocation: tt.location},
|
||||
ConfigurationPerRequest: ConfigurationPerRequest{
|
||||
Requests: []requestDefinition{
|
||||
|
|
@ -742,7 +737,7 @@ func TestWorkaroundsStringRegisterLocationInvalid(t *testing.T) {
|
|||
Name: "Test",
|
||||
Controller: "tcp://localhost:1502",
|
||||
ConfigurationType: "request",
|
||||
Log: testutil.Logger{},
|
||||
Log: testutil.Logger{Quiet: true},
|
||||
Workarounds: ModbusWorkarounds{StringRegisterLocation: "foo"},
|
||||
}
|
||||
require.ErrorContains(t, plugin.Init(), `invalid 'string_register_location'`)
|
||||
|
|
|
|||
|
|
@ -11,8 +11,8 @@ import (
|
|||
"strings"
|
||||
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/config"
|
||||
"github.com/influxdata/telegraf/filter"
|
||||
"github.com/influxdata/telegraf/models"
|
||||
"github.com/influxdata/telegraf/plugins/inputs"
|
||||
"github.com/influxdata/telegraf/plugins/inputs/system"
|
||||
)
|
||||
|
|
@ -35,7 +35,7 @@ func (*NetIOStats) SampleConfig() string {
|
|||
|
||||
func (n *NetIOStats) Init() error {
|
||||
if !n.IgnoreProtocolStats {
|
||||
models.PrintOptionValueDeprecationNotice(telegraf.Warn, "inputs.net", "ignore_protocol_stats", "false",
|
||||
config.PrintOptionValueDeprecationNotice("inputs.net", "ignore_protocol_stats", "false",
|
||||
telegraf.DeprecationInfo{
|
||||
Since: "1.27.3",
|
||||
RemovalIn: "1.36.0",
|
||||
|
|
|
|||
|
|
@ -11,7 +11,6 @@ import (
|
|||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/config"
|
||||
"github.com/influxdata/telegraf/internal/snmp"
|
||||
"github.com/influxdata/telegraf/models"
|
||||
"github.com/influxdata/telegraf/plugins/inputs"
|
||||
)
|
||||
|
||||
|
|
@ -84,7 +83,7 @@ func (s *Snmp) Init() error {
|
|||
s.AgentHostTag = "agent_host"
|
||||
}
|
||||
if s.AgentHostTag != "source" {
|
||||
models.PrintOptionValueDeprecationNotice(telegraf.Warn, "inputs.snmp", "agent_host_tag", s.AgentHostTag, telegraf.DeprecationInfo{
|
||||
config.PrintOptionValueDeprecationNotice("inputs.snmp", "agent_host_tag", s.AgentHostTag, telegraf.DeprecationInfo{
|
||||
Since: "1.29.0",
|
||||
Notice: `set to "source" for consistent usage across plugins or safely ignore this message and continue to use the current value`,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -123,7 +123,7 @@ func (c *CommandRunner) Run(timeout time.Duration, command []string, environment
|
|||
|
||||
s = removeWindowsCarriageReturns(s)
|
||||
if s.Len() > 0 {
|
||||
if !telegraf.Debug {
|
||||
if c.log.Level() < telegraf.Debug {
|
||||
c.log.Errorf("Command error: %q", c.truncate(s))
|
||||
} else {
|
||||
c.log.Debugf("Command error: %q", s)
|
||||
|
|
|
|||
|
|
@ -108,7 +108,7 @@ func (g *Groundwork) Init() error {
|
|||
func(fields interface{}, format string, a ...interface{}) {
|
||||
g.Log.Debug(adaptLog(fields, format, a...))
|
||||
},
|
||||
func() bool { return telegraf.Debug },
|
||||
func() bool { return g.Log.Level() >= telegraf.Debug },
|
||||
)
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ import (
|
|||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/config"
|
||||
"github.com/influxdata/telegraf/internal"
|
||||
"github.com/influxdata/telegraf/models"
|
||||
"github.com/influxdata/telegraf/logger"
|
||||
"github.com/influxdata/telegraf/plugins/outputs"
|
||||
"github.com/influxdata/telegraf/plugins/outputs/postgresql/sqltemplate"
|
||||
"github.com/influxdata/telegraf/plugins/outputs/postgresql/utils"
|
||||
|
|
@ -484,7 +484,7 @@ func newPostgresql() *Postgresql {
|
|||
TagTableCreateTemplates: []*sqltemplate.Template{{}},
|
||||
TagTableAddColumnTemplates: []*sqltemplate.Template{{}},
|
||||
RetryMaxBackoff: config.Duration(time.Second * 15),
|
||||
Logger: models.NewLogger("outputs", "postgresql", ""),
|
||||
Logger: logger.NewLogger("outputs", "postgresql", ""),
|
||||
LogLevel: "warn",
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -51,6 +51,22 @@ func NewLogAccumulator(tb testing.TB) *LogAccumulator {
|
|||
}
|
||||
}
|
||||
|
||||
func (la *LogAccumulator) Level() telegraf.LogLevel {
|
||||
switch la.emitLevel {
|
||||
case pgx.LogLevelInfo:
|
||||
return telegraf.Info
|
||||
case pgx.LogLevelWarn:
|
||||
return telegraf.Warn
|
||||
case pgx.LogLevelError:
|
||||
return telegraf.Error
|
||||
case pgx.LogLevelNone:
|
||||
return telegraf.None
|
||||
}
|
||||
return telegraf.Debug
|
||||
}
|
||||
|
||||
func (*LogAccumulator) RegisterErrorCallback(func()) {}
|
||||
|
||||
func (la *LogAccumulator) append(level pgx.LogLevel, format string, args []interface{}) {
|
||||
la.tb.Helper()
|
||||
|
||||
|
|
@ -318,7 +334,7 @@ func TestConnectionIssueAtStartup(t *testing.T) {
|
|||
defer dsn.Destroy()
|
||||
plugin := newPostgresql()
|
||||
plugin.Connection = dsn
|
||||
plugin.Logger = NewLogAccumulator(t)
|
||||
plugin.Logger = testutil.Logger{}
|
||||
plugin.LogLevel = "debug"
|
||||
model := models.NewRunningOutput(
|
||||
plugin,
|
||||
|
|
|
|||
|
|
@ -7,11 +7,11 @@ import (
|
|||
monpb "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb"
|
||||
tspb "google.golang.org/protobuf/types/known/timestamppb"
|
||||
|
||||
"github.com/influxdata/telegraf/models"
|
||||
"github.com/influxdata/telegraf/logger"
|
||||
)
|
||||
|
||||
func TestCreateCounterCacheEntry(t *testing.T) {
|
||||
cc := NewCounterCache(models.NewLogger("outputs", "stackdriver", "TestCreateCounterCacheEntry"))
|
||||
cc := NewCounterCache(logger.NewLogger("outputs", "stackdriver", "TestCreateCounterCacheEntry"))
|
||||
value := &monpb.TypedValue{
|
||||
Value: &monpb.TypedValue_Int64Value{
|
||||
Int64Value: int64(1),
|
||||
|
|
@ -25,7 +25,7 @@ func TestCreateCounterCacheEntry(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestUpdateCounterCacheEntry(t *testing.T) {
|
||||
cc := NewCounterCache(models.NewLogger("outputs", "stackdriver", "TestUpdateCounterCacheEntry"))
|
||||
cc := NewCounterCache(logger.NewLogger("outputs", "stackdriver", "TestUpdateCounterCacheEntry"))
|
||||
now := time.Now().UTC()
|
||||
value := &monpb.TypedValue{
|
||||
Value: &monpb.TypedValue_Int64Value{
|
||||
|
|
@ -63,7 +63,7 @@ func TestUpdateCounterCacheEntry(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCounterCounterCacheEntryReset(t *testing.T) {
|
||||
cc := NewCounterCache(models.NewLogger("outputs", "stackdriver", "TestCounterCounterCacheEntryReset"))
|
||||
cc := NewCounterCache(logger.NewLogger("outputs", "stackdriver", "TestCounterCounterCacheEntryReset"))
|
||||
now := time.Now().UTC()
|
||||
backdatedNow := now.Add(time.Millisecond * -1)
|
||||
value := &monpb.TypedValue{
|
||||
|
|
@ -103,7 +103,7 @@ func TestCounterCounterCacheEntryReset(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestCounterCacheDayRollover(t *testing.T) {
|
||||
cc := NewCounterCache(models.NewLogger("outputs", "stackdriver", "TestCounterCacheDayRollover"))
|
||||
cc := NewCounterCache(logger.NewLogger("outputs", "stackdriver", "TestCounterCacheDayRollover"))
|
||||
now := time.Now().UTC()
|
||||
backdatedNow := now.Add(time.Millisecond * -1)
|
||||
value := &monpb.TypedValue{
|
||||
|
|
|
|||
|
|
@ -16,10 +16,10 @@ import (
|
|||
"github.com/srebhan/protobufquery"
|
||||
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/config"
|
||||
"github.com/influxdata/telegraf/filter"
|
||||
"github.com/influxdata/telegraf/internal"
|
||||
"github.com/influxdata/telegraf/metric"
|
||||
"github.com/influxdata/telegraf/models"
|
||||
"github.com/influxdata/telegraf/plugins/parsers"
|
||||
)
|
||||
|
||||
|
|
@ -93,7 +93,7 @@ func (p *Parser) Init() error {
|
|||
// Required for backward compatibility
|
||||
if len(p.ConfigsXML) > 0 {
|
||||
p.Configs = append(p.Configs, p.ConfigsXML...)
|
||||
models.PrintOptionDeprecationNotice(telegraf.Warn, "parsers.xpath", "xml", telegraf.DeprecationInfo{
|
||||
config.PrintOptionDeprecationNotice("parsers.xpath", "xml", telegraf.DeprecationInfo{
|
||||
Since: "1.23.1",
|
||||
RemovalIn: "2.0.0",
|
||||
Notice: "use 'xpath' instead",
|
||||
|
|
@ -107,7 +107,7 @@ func (p *Parser) Init() error {
|
|||
// Required for backward compatibility
|
||||
if len(p.ConfigsJSON) > 0 {
|
||||
p.Configs = append(p.Configs, p.ConfigsJSON...)
|
||||
models.PrintOptionDeprecationNotice(telegraf.Warn, "parsers.xpath", "xpath_json", telegraf.DeprecationInfo{
|
||||
config.PrintOptionDeprecationNotice("parsers.xpath", "xpath_json", telegraf.DeprecationInfo{
|
||||
Since: "1.23.1",
|
||||
RemovalIn: "2.0.0",
|
||||
Notice: "use 'xpath' instead",
|
||||
|
|
@ -119,7 +119,7 @@ func (p *Parser) Init() error {
|
|||
// Required for backward compatibility
|
||||
if len(p.ConfigsMsgPack) > 0 {
|
||||
p.Configs = append(p.Configs, p.ConfigsMsgPack...)
|
||||
models.PrintOptionDeprecationNotice(telegraf.Warn, "parsers.xpath", "xpath_msgpack", telegraf.DeprecationInfo{
|
||||
config.PrintOptionDeprecationNotice("parsers.xpath", "xpath_msgpack", telegraf.DeprecationInfo{
|
||||
Since: "1.23.1",
|
||||
RemovalIn: "2.0.0",
|
||||
Notice: "use 'xpath' instead",
|
||||
|
|
@ -141,7 +141,7 @@ func (p *Parser) Init() error {
|
|||
// Required for backward compatibility
|
||||
if len(p.ConfigsProto) > 0 {
|
||||
p.Configs = append(p.Configs, p.ConfigsProto...)
|
||||
models.PrintOptionDeprecationNotice(telegraf.Warn, "parsers.xpath", "xpath_proto", telegraf.DeprecationInfo{
|
||||
config.PrintOptionDeprecationNotice("parsers.xpath", "xpath_proto", telegraf.DeprecationInfo{
|
||||
Since: "1.23.1",
|
||||
RemovalIn: "2.0.0",
|
||||
Notice: "use 'xpath' instead",
|
||||
|
|
@ -157,35 +157,35 @@ func (p *Parser) Init() error {
|
|||
}
|
||||
|
||||
// Update the configs with default values
|
||||
for i, config := range p.Configs {
|
||||
if config.Selection == "" {
|
||||
config.Selection = "/"
|
||||
for i, cfg := range p.Configs {
|
||||
if cfg.Selection == "" {
|
||||
cfg.Selection = "/"
|
||||
}
|
||||
if config.TimestampFmt == "" {
|
||||
config.TimestampFmt = "unix"
|
||||
if cfg.TimestampFmt == "" {
|
||||
cfg.TimestampFmt = "unix"
|
||||
}
|
||||
if config.Timezone == "" {
|
||||
config.Location = time.UTC
|
||||
if cfg.Timezone == "" {
|
||||
cfg.Location = time.UTC
|
||||
} else {
|
||||
loc, err := time.LoadLocation(config.Timezone)
|
||||
loc, err := time.LoadLocation(cfg.Timezone)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid location in config %d: %w", i+1, err)
|
||||
}
|
||||
config.Location = loc
|
||||
cfg.Location = loc
|
||||
}
|
||||
f, err := filter.Compile(config.FieldsHex)
|
||||
f, err := filter.Compile(cfg.FieldsHex)
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating hex-fields filter failed: %w", err)
|
||||
}
|
||||
config.FieldsHexFilter = f
|
||||
cfg.FieldsHexFilter = f
|
||||
|
||||
bf, err := filter.Compile(config.FieldsBase64)
|
||||
bf, err := filter.Compile(cfg.FieldsBase64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating base64-fields filter failed: %w", err)
|
||||
}
|
||||
config.FieldsBase64Filter = bf
|
||||
cfg.FieldsBase64Filter = bf
|
||||
|
||||
p.Configs[i] = config
|
||||
p.Configs[i] = cfg
|
||||
}
|
||||
|
||||
return nil
|
||||
|
|
@ -206,19 +206,19 @@ func (p *Parser) Parse(buf []byte) ([]telegraf.Metric, error) {
|
|||
// Queries
|
||||
metrics := make([]telegraf.Metric, 0)
|
||||
p.Log.Debugf("Number of configs: %d", len(p.Configs))
|
||||
for _, config := range p.Configs {
|
||||
selectedNodes, err := p.document.QueryAll(doc, config.Selection)
|
||||
for _, cfg := range p.Configs {
|
||||
selectedNodes, err := p.document.QueryAll(doc, cfg.Selection)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if (len(selectedNodes) < 1 || selectedNodes[0] == nil) && !p.AllowEmptySelection {
|
||||
p.debugEmptyQuery("metric selection", doc, config.Selection)
|
||||
p.debugEmptyQuery("metric selection", doc, cfg.Selection)
|
||||
return metrics, errors.New("cannot parse with empty selection node")
|
||||
}
|
||||
p.Log.Debugf("Number of selected metric nodes: %d", len(selectedNodes))
|
||||
|
||||
for _, selected := range selectedNodes {
|
||||
m, err := p.parseQuery(t, doc, selected, config)
|
||||
m, err := p.parseQuery(t, doc, selected, cfg)
|
||||
if err != nil {
|
||||
return metrics, err
|
||||
}
|
||||
|
|
@ -250,15 +250,15 @@ func (p *Parser) SetDefaultTags(tags map[string]string) {
|
|||
p.DefaultTags = tags
|
||||
}
|
||||
|
||||
func (p *Parser) parseQuery(starttime time.Time, doc, selected dataNode, config Config) (telegraf.Metric, error) {
|
||||
func (p *Parser) parseQuery(starttime time.Time, doc, selected dataNode, cfg Config) (telegraf.Metric, error) {
|
||||
var timestamp time.Time
|
||||
var metricname string
|
||||
|
||||
// Determine the metric name. If a query was specified, use the result of this query and the default metric name
|
||||
// otherwise.
|
||||
metricname = p.DefaultMetricName
|
||||
if len(config.MetricQuery) > 0 {
|
||||
v, err := p.executeQuery(doc, selected, config.MetricQuery)
|
||||
if len(cfg.MetricQuery) > 0 {
|
||||
v, err := p.executeQuery(doc, selected, cfg.MetricQuery)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to query metric name: %w", err)
|
||||
}
|
||||
|
|
@ -274,13 +274,13 @@ func (p *Parser) parseQuery(starttime time.Time, doc, selected dataNode, config
|
|||
// By default take the time the parser was invoked and override the value
|
||||
// with the queried timestamp if an expression was specified.
|
||||
timestamp = starttime
|
||||
if len(config.Timestamp) > 0 {
|
||||
v, err := p.executeQuery(doc, selected, config.Timestamp)
|
||||
if len(cfg.Timestamp) > 0 {
|
||||
v, err := p.executeQuery(doc, selected, cfg.Timestamp)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to query timestamp: %w", err)
|
||||
}
|
||||
if v != nil {
|
||||
timestamp, err = internal.ParseTimestamp(config.TimestampFmt, v, config.Location)
|
||||
timestamp, err = internal.ParseTimestamp(cfg.TimestampFmt, v, cfg.Location)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse timestamp: %w", err)
|
||||
}
|
||||
|
|
@ -291,18 +291,18 @@ func (p *Parser) parseQuery(starttime time.Time, doc, selected dataNode, config
|
|||
tags := make(map[string]string)
|
||||
|
||||
// Handle the tag batch definitions if any.
|
||||
if len(config.TagSelection) > 0 {
|
||||
if len(cfg.TagSelection) > 0 {
|
||||
tagnamequery := "name()"
|
||||
tagvaluequery := "."
|
||||
if len(config.TagNameQuery) > 0 {
|
||||
tagnamequery = config.TagNameQuery
|
||||
if len(cfg.TagNameQuery) > 0 {
|
||||
tagnamequery = cfg.TagNameQuery
|
||||
}
|
||||
if len(config.TagValueQuery) > 0 {
|
||||
tagvaluequery = config.TagValueQuery
|
||||
if len(cfg.TagValueQuery) > 0 {
|
||||
tagvaluequery = cfg.TagValueQuery
|
||||
}
|
||||
|
||||
// Query all tags
|
||||
selectedTagNodes, err := p.document.QueryAll(selected, config.TagSelection)
|
||||
selectedTagNodes, err := p.document.QueryAll(selected, cfg.TagSelection)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -317,7 +317,7 @@ func (p *Parser) parseQuery(starttime time.Time, doc, selected dataNode, config
|
|||
if !ok {
|
||||
return nil, fmt.Errorf("failed to query tag name with query %q: result is not a string (%v)", tagnamequery, n)
|
||||
}
|
||||
name = p.constructFieldName(selected, selectedtag, name, config.TagNameExpand)
|
||||
name = p.constructFieldName(selected, selectedtag, name, cfg.TagNameExpand)
|
||||
|
||||
v, err := p.executeQuery(doc, selectedtag, tagvaluequery)
|
||||
if err != nil {
|
||||
|
|
@ -343,12 +343,12 @@ func (p *Parser) parseQuery(starttime time.Time, doc, selected dataNode, config
|
|||
tags[name] = s
|
||||
}
|
||||
} else {
|
||||
p.debugEmptyQuery("tag selection", selected, config.TagSelection)
|
||||
p.debugEmptyQuery("tag selection", selected, cfg.TagSelection)
|
||||
}
|
||||
}
|
||||
|
||||
// Handle explicitly defined tags
|
||||
for name, query := range config.Tags {
|
||||
for name, query := range cfg.Tags {
|
||||
// Execute the query and cast the returned values into strings
|
||||
v, err := p.executeQuery(doc, selected, query)
|
||||
if err != nil {
|
||||
|
|
@ -377,18 +377,18 @@ func (p *Parser) parseQuery(starttime time.Time, doc, selected dataNode, config
|
|||
fields := make(map[string]interface{})
|
||||
|
||||
// Handle the field batch definitions if any.
|
||||
if len(config.FieldSelection) > 0 {
|
||||
if len(cfg.FieldSelection) > 0 {
|
||||
fieldnamequery := "name()"
|
||||
fieldvaluequery := "."
|
||||
if len(config.FieldNameQuery) > 0 {
|
||||
fieldnamequery = config.FieldNameQuery
|
||||
if len(cfg.FieldNameQuery) > 0 {
|
||||
fieldnamequery = cfg.FieldNameQuery
|
||||
}
|
||||
if len(config.FieldValueQuery) > 0 {
|
||||
fieldvaluequery = config.FieldValueQuery
|
||||
if len(cfg.FieldValueQuery) > 0 {
|
||||
fieldvaluequery = cfg.FieldValueQuery
|
||||
}
|
||||
|
||||
// Query all fields
|
||||
selectedFieldNodes, err := p.document.QueryAll(selected, config.FieldSelection)
|
||||
selectedFieldNodes, err := p.document.QueryAll(selected, cfg.FieldSelection)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -403,7 +403,7 @@ func (p *Parser) parseQuery(starttime time.Time, doc, selected dataNode, config
|
|||
if !ok {
|
||||
return nil, fmt.Errorf("failed to query field name with query %q: result is not a string (%v)", fieldnamequery, n)
|
||||
}
|
||||
name = p.constructFieldName(selected, selectedfield, name, config.FieldNameExpand)
|
||||
name = p.constructFieldName(selected, selectedfield, name, cfg.FieldNameExpand)
|
||||
|
||||
v, err := p.executeQuery(doc, selectedfield, fieldvaluequery)
|
||||
if err != nil {
|
||||
|
|
@ -427,10 +427,10 @@ func (p *Parser) parseQuery(starttime time.Time, doc, selected dataNode, config
|
|||
switch reflect.TypeOf(v).Kind() {
|
||||
case reflect.Array, reflect.Slice, reflect.Map:
|
||||
if b, ok := v.([]byte); ok {
|
||||
if config.FieldsHexFilter != nil && config.FieldsHexFilter.Match(name) {
|
||||
if cfg.FieldsHexFilter != nil && cfg.FieldsHexFilter.Match(name) {
|
||||
v = hex.EncodeToString(b)
|
||||
}
|
||||
if config.FieldsBase64Filter != nil && config.FieldsBase64Filter.Match(name) {
|
||||
if cfg.FieldsBase64Filter != nil && cfg.FieldsBase64Filter.Match(name) {
|
||||
v = base64.StdEncoding.EncodeToString(b)
|
||||
}
|
||||
} else {
|
||||
|
|
@ -442,12 +442,12 @@ func (p *Parser) parseQuery(starttime time.Time, doc, selected dataNode, config
|
|||
fields[name] = v
|
||||
}
|
||||
} else {
|
||||
p.debugEmptyQuery("field selection", selected, config.FieldSelection)
|
||||
p.debugEmptyQuery("field selection", selected, cfg.FieldSelection)
|
||||
}
|
||||
}
|
||||
|
||||
// Handle explicitly defined fields
|
||||
for name, query := range config.FieldsInt {
|
||||
for name, query := range cfg.FieldsInt {
|
||||
// Execute the query and cast the returned values into integers
|
||||
v, err := p.executeQuery(doc, selected, query)
|
||||
if err != nil {
|
||||
|
|
@ -473,7 +473,7 @@ func (p *Parser) parseQuery(starttime time.Time, doc, selected dataNode, config
|
|||
}
|
||||
}
|
||||
|
||||
for name, query := range config.Fields {
|
||||
for name, query := range cfg.Fields {
|
||||
// Execute the query and store the result in fields
|
||||
v, err := p.executeQuery(doc, selected, query)
|
||||
if err != nil {
|
||||
|
|
@ -486,10 +486,10 @@ func (p *Parser) parseQuery(starttime time.Time, doc, selected dataNode, config
|
|||
switch reflect.TypeOf(v).Kind() {
|
||||
case reflect.Array, reflect.Slice, reflect.Map:
|
||||
if b, ok := v.([]byte); ok {
|
||||
if config.FieldsHexFilter != nil && config.FieldsHexFilter.Match(name) {
|
||||
if cfg.FieldsHexFilter != nil && cfg.FieldsHexFilter.Match(name) {
|
||||
v = hex.EncodeToString(b)
|
||||
}
|
||||
if config.FieldsBase64Filter != nil && config.FieldsBase64Filter.Match(name) {
|
||||
if cfg.FieldsBase64Filter != nil && cfg.FieldsBase64Filter.Match(name) {
|
||||
v = base64.StdEncoding.EncodeToString(b)
|
||||
}
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/influxdata/telegraf"
|
||||
"github.com/influxdata/telegraf/models"
|
||||
"github.com/influxdata/telegraf/config"
|
||||
)
|
||||
|
||||
var (
|
||||
|
|
@ -47,8 +47,8 @@ func (m *TemplateMetric) String() string {
|
|||
|
||||
func (m *TemplateMetric) TagList() map[string]string {
|
||||
onceTagList.Do(func() {
|
||||
models.PrintOptionValueDeprecationNotice(
|
||||
telegraf.Warn, "processors.template", "template", "{{.TagList}}",
|
||||
config.PrintOptionValueDeprecationNotice(
|
||||
"processors.template", "template", "{{.TagList}}",
|
||||
telegraf.DeprecationInfo{
|
||||
Since: "1.28.0",
|
||||
RemovalIn: "1.34.0",
|
||||
|
|
@ -61,8 +61,8 @@ func (m *TemplateMetric) TagList() map[string]string {
|
|||
|
||||
func (m *TemplateMetric) FieldList() map[string]interface{} {
|
||||
onceFieldList.Do(func() {
|
||||
models.PrintOptionValueDeprecationNotice(
|
||||
telegraf.Warn, "processors.template", "template", "{{.FieldList}}",
|
||||
config.PrintOptionValueDeprecationNotice(
|
||||
"processors.template", "template", "{{.FieldList}}",
|
||||
telegraf.DeprecationInfo{
|
||||
Since: "1.28.0",
|
||||
RemovalIn: "1.34.0",
|
||||
|
|
|
|||
|
|
@ -49,6 +49,12 @@ func (l *CaptureLogger) loga(level byte, args ...any) {
|
|||
l.print(Entry{level, l.Name, fmt.Sprint(args...)})
|
||||
}
|
||||
|
||||
func (l *CaptureLogger) Level() telegraf.LogLevel {
|
||||
return telegraf.Debug
|
||||
}
|
||||
|
||||
func (*CaptureLogger) RegisterErrorCallback(func()) {}
|
||||
|
||||
// Errorf logs an error message, patterned after log.Printf.
|
||||
func (l *CaptureLogger) Errorf(format string, args ...interface{}) {
|
||||
l.logf(LevelError, format, args...)
|
||||
|
|
|
|||
|
|
@ -14,6 +14,12 @@ type Logger struct {
|
|||
Quiet bool
|
||||
}
|
||||
|
||||
func (l Logger) Level() telegraf.LogLevel {
|
||||
return telegraf.Debug
|
||||
}
|
||||
|
||||
func (Logger) RegisterErrorCallback(func()) {}
|
||||
|
||||
// Errorf logs an error message, patterned after log.Printf.
|
||||
func (l Logger) Errorf(format string, args ...interface{}) {
|
||||
log.Printf("E! ["+l.Name+"] "+format, args...)
|
||||
|
|
|
|||
Loading…
Reference in New Issue