|
| 1 | +package logger |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + |
| 6 | + "github.com/Azure/azure-container-networking/internal/time" |
| 7 | + "github.com/Azure/azure-container-networking/zapai" |
| 8 | + "github.com/microsoft/ApplicationInsights-Go/appinsights" |
| 9 | + "github.com/pkg/errors" |
| 10 | + "go.uber.org/zap" |
| 11 | + "go.uber.org/zap/zapcore" |
| 12 | +) |
| 13 | + |
| 14 | +type AppInsightsConfig struct { |
| 15 | + level zapcore.Level `json:"-"` // Zero value is default Info level. |
| 16 | + Level string `json:"level"` |
| 17 | + IKey string `json:"ikey"` |
| 18 | + GracePeriod time.Duration `json:"grace_period"` |
| 19 | + MaxBatchInterval time.Duration `json:"max_batch_interval"` |
| 20 | + MaxBatchSize int `json:"max_batch_size"` |
| 21 | + Fields []zapcore.Field `json:"fields"` |
| 22 | +} |
| 23 | + |
| 24 | +// UnmarshalJSON implements json.Unmarshaler for the Config. |
| 25 | +// It only differs from the default by parsing the |
| 26 | +// Level string into a zapcore.Level and setting the level field. |
| 27 | +func (c *AppInsightsConfig) UnmarshalJSON(data []byte) error { |
| 28 | + type Alias AppInsightsConfig |
| 29 | + aux := &struct { |
| 30 | + *Alias |
| 31 | + }{ |
| 32 | + Alias: (*Alias)(c), |
| 33 | + } |
| 34 | + if err := json.Unmarshal(data, &aux); err != nil { |
| 35 | + return errors.Wrap(err, "failed to unmarshal AppInsightsConfig") |
| 36 | + } |
| 37 | + lvl, err := zapcore.ParseLevel(c.Level) |
| 38 | + if err != nil { |
| 39 | + return errors.Wrap(err, "failed to parse AppInsightsConfig Level") |
| 40 | + } |
| 41 | + c.level = lvl |
| 42 | + return nil |
| 43 | +} |
| 44 | + |
| 45 | +// ApplicationInsightsCore builds a zapcore.Core that sends logs to Application Insights. |
| 46 | +// The first return is the core, the second is a function to close the sink. |
| 47 | +func ApplicationInsightsCore(cfg *AppInsightsConfig) (zapcore.Core, func(), error) { |
| 48 | + // build the AI config |
| 49 | + aicfg := *appinsights.NewTelemetryConfiguration(cfg.IKey) |
| 50 | + aicfg.MaxBatchSize = cfg.MaxBatchSize |
| 51 | + aicfg.MaxBatchInterval = cfg.MaxBatchInterval.Duration |
| 52 | + sinkcfg := zapai.SinkConfig{ |
| 53 | + GracePeriod: cfg.GracePeriod.Duration, |
| 54 | + TelemetryConfiguration: aicfg, |
| 55 | + } |
| 56 | + // open the AI zap sink |
| 57 | + sink, aiclose, err := zap.Open(sinkcfg.URI()) |
| 58 | + if err != nil { |
| 59 | + return nil, aiclose, errors.Wrap(err, "failed to open AI sink") |
| 60 | + } |
| 61 | + // build the AI core |
| 62 | + core := zapai.NewCore(cfg.level, sink) |
| 63 | + core = core.WithFieldMappers(zapai.DefaultMappers) |
| 64 | + // add normalized fields for the built-in AI Tags |
| 65 | + // TODO(rbtr): move to the caller |
| 66 | + return core.With(cfg.Fields), aiclose, nil |
| 67 | +} |
0 commit comments