aurganize-backend/backend/pkg/logger/examples_test.go

108 lines
2.5 KiB
Go

package logger_test
import (
"time"
"github.com/creativenoz/aurganize-v62/backend/pkg/logger"
"github.com/rs/zerolog/log"
)
// Example_basicUsage demonstrates basic logger usage
func Example_basicUsage() {
// Initialize logger
logger.Init("development")
// Log at different levels
log.Debug().Msg("This is debug information")
log.Info().Msg("This is informational")
log.Warn().Msg("This is a warning")
log.Error().Msg("This is an error")
// Output depends on log level
}
// Example_structuredLogging demonstrates structured logging with fields
func Example_structuredLogging() {
logger.Init("development")
// Log with structured fields
log.Info().
Str("user_id", "12345").
Str("action", "login").
Bool("success", true).
Dur("duration", 150*time.Millisecond).
Msg("User login attempt")
// JSON output:
// {
// "level": "info",
// "user_id": "12345",
// "action": "login",
// "success": true,
// "duration": 150,
// "message": "User login attempt"
// }
}
// Example_contextLogger demonstrates creating logger with context
func Example_contextLogger() {
logger.Init("development")
// Create logger with request context
requestLogger := logger.WithContext(map[string]interface{}{
"request_id": "req-abc-123",
"user_id": "user-456",
"ip": "192.168.1.1",
})
// All logs from this logger include context
requestLogger.Info().Msg("Request started")
requestLogger.Info().Msg("Processing payment")
requestLogger.Info().Msg("Request completed")
// All three logs include request_id, user_id, and ip
}
// Example_errorLogging demonstrates logging errors
func Example_errorLogging() {
logger.Init("development")
// Simulate an error
err := someFunction()
if err != nil {
log.Error().
Err(err). // Add error
Str("user_id", "123").
Str("operation", "database_query").
Msg("Failed to fetch user")
}
}
// Example_subLogger demonstrates module-specific loggers
func Example_subLogger() {
logger.Init("development")
// Create a sub-logger for authentication module
authLogger := log.With().
Str("module", "auth").
Str("version", "v1").
Logger()
authLogger.Info().Msg("Auth module initialized")
authLogger.Debug().Msg("Loading auth configuration")
// Create a sub-logger for database module
dbLogger := log.With().
Str("module", "database").
Logger()
dbLogger.Info().Msg("Database connection established")
// Now you can filter logs by module in production
}
// Helper function for example
func someFunction() error {
return nil
}