Basic Logging
ByteHide Logger provides six logging levels with simple, intuitive functions. Each level serves different purposes and supports various parameters for flexible logging.
Logging Methods Overview
| Method | Purpose |
|---|---|
logs.Trace(message) | Most detailed diagnostic information |
logs.Debug(message) | Detailed diagnostic information |
logs.Info(message) | General information messages |
logs.Warn(message) | Warning messages |
logs.Error(message, err) | Error messages with error object |
logs.Critical(message) | Critical errors |
Basic Logging Methods
Trace Level
Use for the most detailed diagnostic information:
import "github.com/bytehide/bytehide-logs-go"
logs.Trace("Entering goroutine processOrder")
logs.Trace("Processing item 1 of 10")
logs.Trace("Database connection established")import "github.com/bytehide/bytehide-logs-go"
logs.Trace("Entering goroutine processOrder")
logs.Trace("Processing item 1 of 10")
logs.Trace("Database connection established")Debug Level
Use for detailed diagnostic information during development:
logs.Debug("User authentication started")
logs.Debug("Cache miss for key: user_123")
logs.Debug("API response received in 250ms")logs.Debug("User authentication started")
logs.Debug("Cache miss for key: user_123")
logs.Debug("API response received in 250ms")Info Level
Use for general information about application flow:
logs.Info("Application started successfully")
logs.Info("User logged in")
logs.Info("Order processed successfully")logs.Info("Application started successfully")
logs.Info("User logged in")
logs.Info("Order processed successfully")Advanced Logging Methods
Warn Level
Use for potential issues that don't stop execution:
logs.Warn("API rate limit approaching")
result, err := someOperation()
if err != nil {
logs.Warn("Non-critical operation failed, using fallback")
}logs.Warn("API rate limit approaching")
result, err := someOperation()
if err != nil {
logs.Warn("Non-critical operation failed, using fallback")
}Error Level
Use for errors that affect functionality:
order, err := processOrder(orderId)
if err != nil {
logs.Error("Failed to process order", err)
return nil, err
}order, err := processOrder(orderId)
if err != nil {
logs.Error("Failed to process order", err)
return nil, err
}Critical Level
Use for critical errors that may cause application termination:
err := initializeDatabase()
if err != nil {
logs.Critical("Failed to initialize database - application cannot continue")
os.Exit(1)
}err := initializeDatabase()
if err != nil {
logs.Critical("Failed to initialize database - application cannot continue")
os.Exit(1)
}Direct API with Tags and Context
Package-level functions provide straightforward logging without fluent chains:
import (
"github.com/bytehide/bytehide-logs-go"
)
// Basic info logging
logs.Info("User logged in")
// Error logging with error object
err := someOperation()
if err != nil {
logs.Error("Operation failed", err)
}
// Trace with detailed message
logs.Trace("Processing request: " + requestID)import (
"github.com/bytehide/bytehide-logs-go"
)
// Basic info logging
logs.Info("User logged in")
// Error logging with error object
err := someOperation()
if err != nil {
logs.Error("Operation failed", err)
}
// Trace with detailed message
logs.Trace("Processing request: " + requestID)Fluent Syntax
ByteHide Logger supports fluent syntax for combining multiple features:
// Combine context and tags
logs.WithContext("orderId", "ORD-001").
WithContext("customerId", "CUST-123").
WithTags("orders", "critical").
Error("Order processing failed", err)
// With metadata
logs.WithContext("executionTimeMs", 1250).
WithContext("sqlQuery", "SELECT * FROM orders").
WithTags("database", "performance").
Warn("Slow database query detected")
// Chain multiple tags
logs.WithTags("auth", "login", "user").
WithContext("userId", userID).
Info("User authentication successful")// Combine context and tags
logs.WithContext("orderId", "ORD-001").
WithContext("customerId", "CUST-123").
WithTags("orders", "critical").
Error("Order processing failed", err)
// With metadata
logs.WithContext("executionTimeMs", 1250).
WithContext("sqlQuery", "SELECT * FROM orders").
WithTags("database", "performance").
Warn("Slow database query detected")
// Chain multiple tags
logs.WithTags("auth", "login", "user").
WithContext("userId", userID).
Info("User authentication successful")Learn More About Fluent Syntax
For comprehensive examples and advanced patterns, see Fluent Syntax.
Error Logging
Go error handling uses explicit error return values instead of exceptions:
// Direct error logging
result, err := riskyOperation()
if err != nil {
logs.Error("Operation failed", err)
return nil, err
}
// With fluent API
result, err := processPayment(paymentRequest)
if err != nil {
logs.WithTags("error", "critical").
WithException(err).
Error("Critical operation failed", err)
return nil, err
}// Direct error logging
result, err := riskyOperation()
if err != nil {
logs.Error("Operation failed", err)
return nil, err
}
// With fluent API
result, err := processPayment(paymentRequest)
if err != nil {
logs.WithTags("error", "critical").
WithException(err).
Error("Critical operation failed", err)
return nil, err
}Practical Examples
Service Layer Logging
type OrderService struct {
repo OrderRepository
}
func (s *OrderService) CreateOrder(request *CreateOrderRequest) (*Order, error) {
logs.Info("Creating new order")
logs.Debug("Validating order request")
// Validate request
if request == nil {
logs.Warn("Order validation failed: nil request")
return nil, fmt.Errorf("invalid request")
}
logs.Trace("Order request validated")
order := &Order{
ID: generateID(),
CustomerID: request.CustomerID,
}
logs.Trace("Order object created")
err := s.repo.Save(order)
if err != nil {
logs.WithContext("customerId", request.CustomerID).
Error("Failed to create order", err)
return nil, err
}
logs.Info("Order created successfully")
return order, nil
}type OrderService struct {
repo OrderRepository
}
func (s *OrderService) CreateOrder(request *CreateOrderRequest) (*Order, error) {
logs.Info("Creating new order")
logs.Debug("Validating order request")
// Validate request
if request == nil {
logs.Warn("Order validation failed: nil request")
return nil, fmt.Errorf("invalid request")
}
logs.Trace("Order request validated")
order := &Order{
ID: generateID(),
CustomerID: request.CustomerID,
}
logs.Trace("Order object created")
err := s.repo.Save(order)
if err != nil {
logs.WithContext("customerId", request.CustomerID).
Error("Failed to create order", err)
return nil, err
}
logs.Info("Order created successfully")
return order, nil
}HTTP Handler with Logging
func (h *OrderHandler) HandleCreateOrder(w http.ResponseWriter, r *http.Request) {
logs.WithContext("method", r.Method).
WithContext("path", r.RequestURI).
Debug("Processing request")
defer func() {
if err := recover(); err != nil {
logs.Critical("Panic in order handler")
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}()
var req CreateOrderRequest
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
logs.Error("Failed to decode request", err)
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
order, err := h.service.CreateOrder(&req)
if err != nil {
logs.Error("Order creation failed", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
logs.Info("Order created successfully")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(order)
}func (h *OrderHandler) HandleCreateOrder(w http.ResponseWriter, r *http.Request) {
logs.WithContext("method", r.Method).
WithContext("path", r.RequestURI).
Debug("Processing request")
defer func() {
if err := recover(); err != nil {
logs.Critical("Panic in order handler")
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}()
var req CreateOrderRequest
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
logs.Error("Failed to decode request", err)
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
order, err := h.service.CreateOrder(&req)
if err != nil {
logs.Error("Order creation failed", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
logs.Info("Order created successfully")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(order)
}Database Operation with Logging
func (r *OrderRepository) GetOrderByID(ctx context.Context, orderID string) (*Order, error) {
logs.WithContext("orderId", orderID).
Trace("Retrieving order from database")
query := "SELECT id, customer_id, total FROM orders WHERE id = $1"
row := r.db.QueryRowContext(ctx, query, orderID)
var order Order
err := row.Scan(&order.ID, &order.CustomerID, &order.Total)
if err != nil {
if err == sql.ErrNoRows {
logs.WithContext("orderId", orderID).
Debug("Order not found in database")
return nil, fmt.Errorf("order not found")
}
logs.WithContext("orderId", orderID).
Error("Database query failed", err)
return nil, err
}
logs.WithContext("orderId", orderID).
Trace("Order retrieved successfully")
return &order, nil
}func (r *OrderRepository) GetOrderByID(ctx context.Context, orderID string) (*Order, error) {
logs.WithContext("orderId", orderID).
Trace("Retrieving order from database")
query := "SELECT id, customer_id, total FROM orders WHERE id = $1"
row := r.db.QueryRowContext(ctx, query, orderID)
var order Order
err := row.Scan(&order.ID, &order.CustomerID, &order.Total)
if err != nil {
if err == sql.ErrNoRows {
logs.WithContext("orderId", orderID).
Debug("Order not found in database")
return nil, fmt.Errorf("order not found")
}
logs.WithContext("orderId", orderID).
Error("Database query failed", err)
return nil, err
}
logs.WithContext("orderId", orderID).
Trace("Order retrieved successfully")
return &order, nil
}Best Practices
When to Use Each Level
- Trace: Function entry/exit, goroutine lifecycle, loop iterations, detailed flow
- Debug: Variable values, cache hits/misses, intermediate results
- Info: Application milestones, user actions, business events
- Warn: Recoverable errors, deprecated usage, performance issues
- Error: Explicit error returns, failed operations, data inconsistencies
- Critical: System failures, security breaches, unrecoverable errors
Go Error Handling Pattern
In Go, always check error values explicitly using if err != nil. Use logs.Error() to log errors along with the error object for full context and stack trace capture.