Skip to content

Commit 57c4245

Browse files
committed
improve the logging
1 parent 0beafb6 commit 57c4245

File tree

3 files changed

+238
-170
lines changed

3 files changed

+238
-170
lines changed

cns/cni-telemetry-sidecar/configmanager.go

Lines changed: 62 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -4,104 +4,98 @@ import (
44
"encoding/json"
55
"fmt"
66
"os"
7-
"time"
87

98
"github.com/Azure/azure-container-networking/cns/configuration"
10-
"github.com/Azure/azure-container-networking/cns/logger"
9+
"go.uber.org/zap"
1110
)
1211

13-
// ConfigManager handles Azure CNS configuration loading and validation
12+
// ConfigManager handles CNS configuration loading
1413
type ConfigManager struct {
1514
configPath string
15+
logger *zap.Logger
1616
}
1717

18-
// NewConfigManager creates a new configuration manager for Azure CNS
18+
// NewConfigManager creates a new config manager
1919
func NewConfigManager(configPath string) *ConfigManager {
2020
return &ConfigManager{
2121
configPath: configPath,
2222
}
2323
}
2424

25-
// LoadConfig loads and validates the Azure CNS configuration
25+
// SetLogger sets the zap logger for the config manager
26+
func (cm *ConfigManager) SetLogger(logger *zap.Logger) {
27+
cm.logger = logger
28+
}
29+
30+
// LoadConfig loads the CNS configuration from file
2631
func (cm *ConfigManager) LoadConfig() (*configuration.CNSConfig, error) {
27-
logger.Printf("Loading Azure CNS configuration from: %s", cm.configPath)
32+
// Use zap logger if available, otherwise create a default config
33+
if cm.logger != nil {
34+
cm.logger.Debug("Loading CNS configuration", zap.String("path", cm.configPath))
35+
}
2836

29-
// Wait for configuration file to become available (Kubernetes ConfigMap mount)
30-
if err := cm.waitForConfigFile(); err != nil {
31-
return nil, fmt.Errorf("Azure CNS configuration file not available: %w", err)
37+
// Check if config file exists
38+
if _, err := os.Stat(cm.configPath); os.IsNotExist(err) {
39+
if cm.logger != nil {
40+
cm.logger.Info("CNS config file not found, using default configuration",
41+
zap.String("path", cm.configPath))
42+
}
43+
44+
// Return default configuration
45+
return &configuration.CNSConfig{
46+
TelemetrySettings: configuration.TelemetrySettings{
47+
DisableAll: false,
48+
TelemetryBatchSizeBytes: 16384,
49+
TelemetryBatchIntervalInSecs: 15,
50+
RefreshIntervalInSecs: 15,
51+
DisableMetadataRefreshThread: false,
52+
DebugMode: false,
53+
DisableTrace: false,
54+
DisableMetric: false,
55+
DisableEvent: false,
56+
AppInsightsInstrumentationKey: "", // Will be set by environment or config
57+
},
58+
}, nil
3259
}
3360

34-
// Read the configuration file from mounted volume
61+
// Read the config file
3562
data, err := os.ReadFile(cm.configPath)
3663
if err != nil {
37-
return nil, fmt.Errorf("failed to read Azure CNS configuration file: %w", err)
64+
if cm.logger != nil {
65+
cm.logger.Error("Failed to read CNS config file",
66+
zap.String("path", cm.configPath),
67+
zap.Error(err))
68+
}
69+
return nil, fmt.Errorf("failed to read config file %s: %w", cm.configPath, err)
3870
}
3971

40-
// Parse JSON configuration into CNS config structure
72+
// Parse the JSON configuration
4173
var config configuration.CNSConfig
4274
if err := json.Unmarshal(data, &config); err != nil {
43-
return nil, fmt.Errorf("failed to parse Azure CNS configuration: %w", err)
44-
}
45-
46-
// Validate configuration for Azure telemetry requirements
47-
if err := cm.validateConfig(&config); err != nil {
48-
return nil, fmt.Errorf("Azure CNS configuration validation failed: %w", err)
49-
}
50-
51-
logger.Printf("Azure CNS configuration loaded and validated successfully")
52-
return &config, nil
53-
}
54-
55-
// waitForConfigFile waits for the configuration file to become available
56-
// This is important in Kubernetes environments where ConfigMaps are mounted asynchronously
57-
func (cm *ConfigManager) waitForConfigFile() error {
58-
const maxRetries = 30
59-
const retryInterval = 2 * time.Second
60-
61-
for i := 0; i < maxRetries; i++ {
62-
if _, err := os.Stat(cm.configPath); err == nil {
63-
return nil
64-
}
65-
66-
if i == 0 {
67-
logger.Printf("Waiting for Azure CNS configuration file to become available...")
75+
if cm.logger != nil {
76+
cm.logger.Error("Failed to parse CNS config file",
77+
zap.String("path", cm.configPath),
78+
zap.Error(err))
6879
}
69-
70-
time.Sleep(retryInterval)
80+
return nil, fmt.Errorf("failed to parse config file: %w", err)
7181
}
7282

73-
return fmt.Errorf("Azure CNS configuration file not available after %d attempts (%v total wait time)",
74-
maxRetries, time.Duration(maxRetries)*retryInterval)
75-
}
76-
77-
// validateConfig performs Azure-specific validation of the CNS configuration
78-
func (cm *ConfigManager) validateConfig(config *configuration.CNSConfig) error {
79-
// Validate that telemetry settings are properly configured
80-
if config.TelemetrySettings.AppInsightsInstrumentationKey == "" && !config.TelemetrySettings.DisableAll {
81-
logger.Printf("Warning: No Application Insights instrumentation key configured and telemetry not disabled")
83+
// Set default values for telemetry settings if not specified
84+
if config.TelemetrySettings.TelemetryBatchSizeBytes == 0 {
85+
config.TelemetrySettings.TelemetryBatchSizeBytes = 16384
8286
}
83-
84-
// Validate batch size settings for Azure Application Insights
85-
if config.TelemetrySettings.TelemetryBatchSizeBytes <= 0 {
86-
logger.Printf("Warning: Invalid telemetry batch size, using default")
87+
if config.TelemetrySettings.TelemetryBatchIntervalInSecs == 0 {
88+
config.TelemetrySettings.TelemetryBatchIntervalInSecs = 15
8789
}
88-
89-
// Validate batch interval for optimal Azure ingestion
90-
if config.TelemetrySettings.TelemetryBatchIntervalInSecs <= 0 {
91-
logger.Printf("Warning: Invalid telemetry batch interval, using default")
90+
if config.TelemetrySettings.RefreshIntervalInSecs == 0 {
91+
config.TelemetrySettings.RefreshIntervalInSecs = 15
9292
}
9393

94-
// Log configuration summary for Azure monitoring and debugging
95-
logger.Printf("Azure CNS Configuration Summary:")
96-
logger.Printf(" - Telemetry DisableAll: %t", config.TelemetrySettings.DisableAll)
97-
logger.Printf(" - Application Insights Key Present: %t",
98-
config.TelemetrySettings.AppInsightsInstrumentationKey != "")
99-
logger.Printf(" - Batch Size: %d bytes", config.TelemetrySettings.TelemetryBatchSizeBytes)
100-
logger.Printf(" - Batch Interval: %d seconds", config.TelemetrySettings.TelemetryBatchIntervalInSecs)
101-
logger.Printf(" - Disable Trace: %t", config.TelemetrySettings.DisableTrace)
102-
logger.Printf(" - Disable Metric: %t", config.TelemetrySettings.DisableMetric)
103-
logger.Printf(" - Disable Event: %t", config.TelemetrySettings.DisableEvent)
104-
logger.Printf(" - Debug Mode: %t", config.TelemetrySettings.DebugMode)
94+
if cm.logger != nil {
95+
cm.logger.Info("Successfully loaded CNS configuration",
96+
zap.String("path", cm.configPath),
97+
zap.Bool("telemetryDisabled", config.TelemetrySettings.DisableAll))
98+
}
10599

106-
return nil
100+
return &config, nil
107101
}

cns/cni-telemetry-sidecar/main.go

Lines changed: 32 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,26 +7,46 @@ import (
77
"os/signal"
88
"syscall"
99

10-
"github.com/Azure/azure-container-networking/cns/logger"
10+
"github.com/Azure/azure-container-networking/cns/logger/v2"
11+
cores "github.com/Azure/azure-container-networking/cns/logger/v2/cores"
12+
"go.uber.org/zap"
1113
)
1214

1315
var (
1416
version = "unknown"
1517
configPath = flag.String("config", "/etc/cns/cns-config.json", "Path to CNS configuration file")
18+
logLevel = flag.String("log-level", "info", "Log level (debug, info, warn, error)")
1619
)
1720

1821
func main() {
1922
flag.Parse()
2023

21-
// Initialize logging for the CNI telemetry sidecar
22-
logger.InitLogger("azure-cns-cni-telemetry-sidecar", 1, 1, "/var/log/azure-cns-telemetry")
23-
defer logger.Close()
24+
// Initialize main logger with correct path for shared volume
25+
zapLogger, cleanup, err := logger.New(&logger.Config{
26+
Level: *logLevel,
27+
File: &cores.FileConfig{
28+
Filepath: "/var/log/azure-cni-telemetry-sidecar.log", // This will write to host's /var/log/azure-cns/
29+
},
30+
})
31+
if err != nil {
32+
panic("Failed to initialize logger: " + err.Error())
33+
}
34+
defer cleanup()
2435

25-
logger.Printf("Starting Azure CNI Telemetry Sidecar v%s", version)
36+
zapLogger.Info("Starting Azure CNI Telemetry Sidecar",
37+
zap.String("version", version),
38+
zap.String("configPath", *configPath),
39+
zap.String("logLevel", *logLevel))
2640

27-
// Create telemetry sidecar service
41+
// Create telemetry sidecar service and pass the logger
2842
sidecar := NewTelemetrySidecar(*configPath)
2943

44+
// Set the logger for the sidecar to avoid nil pointer
45+
if err := sidecar.SetLogger(zapLogger); err != nil {
46+
zapLogger.Error("Failed to set logger for sidecar", zap.Error(err))
47+
os.Exit(1)
48+
}
49+
3050
// Setup graceful shutdown context
3151
ctx, cancel := context.WithCancel(context.Background())
3252
defer cancel()
@@ -37,15 +57,17 @@ func main() {
3757

3858
go func() {
3959
sig := <-sigCh
40-
logger.Printf("Received shutdown signal %v, initiating graceful shutdown", sig)
60+
zapLogger.Info("Received shutdown signal, initiating graceful shutdown",
61+
zap.String("signal", sig.String()))
4162
cancel()
4263
}()
4364

44-
// Run the telemetry sidecar
65+
// Run the telemetry sidecar (using the Run method from sidecar.go)
4566
if err := sidecar.Run(ctx); err != nil {
46-
logger.Errorf("Azure CNI Telemetry Sidecar failed: %v", err)
67+
zapLogger.Error("Azure CNI Telemetry Sidecar failed",
68+
zap.Error(err))
4769
os.Exit(1)
4870
}
4971

50-
logger.Printf("Azure CNI Telemetry Sidecar stopped gracefully")
72+
zapLogger.Info("Azure CNI Telemetry Sidecar stopped gracefully")
5173
}

0 commit comments

Comments
 (0)