Quick Start with ByteHide Logger
Prerequisites
Before you begin, make sure you have:
- A ByteHide account and project token
- Go 1.19 or higher installed
Quick Start Guide
- Install ByteHide Logger in your project
- Initialize the logger with your project token
- Start logging with simple API calls
- View logs in the ByteHide web panel
- Explore advanced features as needed
Step 1: Installation
Add the ByteHide Logger dependency to your project:
Bash
go get github.com/bytehide/bytehide-logs-gogo get github.com/bytehide/bytehide-logs-goStep 2: Basic Setup
Initialize the logger in your application startup:
Go
package main
import (
"fmt"
"os"
"defer"
logs "github.com/bytehide/bytehide-logs-go"
)
func main() {
// Configure the logger
logs.SetProjectToken("your-project-token-here")
logs.SetMinimumLevel(logs.LogLevelInfo)
logs.SetConsoleEnabled(true)
logs.SetPersist(true)
logs.SetFilePath("logs/app.log")
// Ensure logs are flushed and logger is shutdown on exit
defer func() {
logs.Flush()
logs.Shutdown()
}()
// Your application code
runApplication()
}
func runApplication() {
logs.Info("Application started successfully!")
// Simulate some work
processOrder("ORD-001", "CUST-123")
logs.Info("Application finished")
}
func processOrder(orderId, customerId string) {
logs.WithContext("orderId", orderId).
WithContext("customerId", customerId).
Info("Processing order")
// Simulate processing
// ... process order ...
logs.WithContext("orderId", orderId).
WithContext("processingTime", "1.2s").
Info("Order processed successfully")
}package main
import (
"fmt"
"os"
"defer"
logs "github.com/bytehide/bytehide-logs-go"
)
func main() {
// Configure the logger
logs.SetProjectToken("your-project-token-here")
logs.SetMinimumLevel(logs.LogLevelInfo)
logs.SetConsoleEnabled(true)
logs.SetPersist(true)
logs.SetFilePath("logs/app.log")
// Ensure logs are flushed and logger is shutdown on exit
defer func() {
logs.Flush()
logs.Shutdown()
}()
// Your application code
runApplication()
}
func runApplication() {
logs.Info("Application started successfully!")
// Simulate some work
processOrder("ORD-001", "CUST-123")
logs.Info("Application finished")
}
func processOrder(orderId, customerId string) {
logs.WithContext("orderId", orderId).
WithContext("customerId", customerId).
Info("Processing order")
// Simulate processing
// ... process order ...
logs.WithContext("orderId", orderId).
WithContext("processingTime", "1.2s").
Info("Order processed successfully")
}Step 3: Basic Logging
Use the simple logging API throughout your application:
Go
package main
import (
logs "github.com/bytehide/bytehide-logs-go"
)
type UserService struct {
database Database
}
func (us *UserService) GetUser(userId string) (*User, error) {
logs.Debug().WithContext("userId", userId).Log("Fetching user")
user, err := us.database.GetUser(userId)
if err != nil {
logs.Error("Failed to retrieve user", err)
return nil, err
}
logs.WithContext("userId", userId).
WithContext("username", user.Username).
Info("User retrieved successfully")
return user, nil
}
func (us *UserService) CreateUser(user *User) error {
logs.WithContext("username", user.Username).
WithContext("email", user.Email).
Info("Creating new user")
err := us.database.CreateUser(user)
if err != nil {
logs.Error("Failed to create user", err)
return err
}
logs.WithContext("userId", user.ID).
Info("User created successfully")
return nil
}package main
import (
logs "github.com/bytehide/bytehide-logs-go"
)
type UserService struct {
database Database
}
func (us *UserService) GetUser(userId string) (*User, error) {
logs.Debug().WithContext("userId", userId).Log("Fetching user")
user, err := us.database.GetUser(userId)
if err != nil {
logs.Error("Failed to retrieve user", err)
return nil, err
}
logs.WithContext("userId", userId).
WithContext("username", user.Username).
Info("User retrieved successfully")
return user, nil
}
func (us *UserService) CreateUser(user *User) error {
logs.WithContext("username", user.Username).
WithContext("email", user.Email).
Info("Creating new user")
err := us.database.CreateUser(user)
if err != nil {
logs.Error("Failed to create user", err)
return err
}
logs.WithContext("userId", user.ID).
Info("User created successfully")
return nil
}Step 4: Advanced Logging Features
Structured Logging with Context
Go
// Add context to your logs
logs.WithContext("userId", "12345").
WithContext("sessionId", "sess-abc").
Info("User performed action")
// Use tags for categorization
logs.WithTags("payment", "critical").
Info("Payment processing started")
// Combine context and tags
logs.WithContext("orderId", "ORD-001").
WithContext("amount", 99.99).
WithTags("payment", "success").
Info("Payment completed")// Add context to your logs
logs.WithContext("userId", "12345").
WithContext("sessionId", "sess-abc").
Info("User performed action")
// Use tags for categorization
logs.WithTags("payment", "critical").
Info("Payment processing started")
// Combine context and tags
logs.WithContext("orderId", "ORD-001").
WithContext("amount", 99.99).
WithTags("payment", "success").
Info("Payment completed")User Identification
Go
// Identify the current user
user := &logs.AuthUser{
ID: "user-123",
Email: "john.doe@company.com",
Token: "token-xyz",
}
logs.SetUser(user)
// All subsequent logs will include user information
logs.Info("User action performed")
logs.Warn("User attempted unauthorized action")// Identify the current user
user := &logs.AuthUser{
ID: "user-123",
Email: "john.doe@company.com",
Token: "token-xyz",
}
logs.SetUser(user)
// All subsequent logs will include user information
logs.Info("User action performed")
logs.Warn("User attempted unauthorized action")Correlation IDs
Go
import "fmt"
// Set correlation ID for request tracking
correlationId := fmt.Sprintf("req_%d", time.Now().UnixNano())
logs.WithCorrelationID(correlationId).Info("Request started")
logs.WithCorrelationID(correlationId).Info("Processing data")
logs.WithCorrelationID(correlationId).Info("Request completed")import "fmt"
// Set correlation ID for request tracking
correlationId := fmt.Sprintf("req_%d", time.Now().UnixNano())
logs.WithCorrelationID(correlationId).Info("Request started")
logs.WithCorrelationID(correlationId).Info("Processing data")
logs.WithCorrelationID(correlationId).Info("Request completed")Step 5: Production Configuration
For production environments, use a more comprehensive configuration:
Go
import (
"os"
logs "github.com/bytehide/bytehide-logs-go"
)
func initializeProductionLogger() {
// Log levels
logs.SetMinimumLevel(logs.LogLevelWarn)
// File logging
logs.SetPersist(true)
logs.SetFilePath("logs/production.log")
logs.SetRollingInterval(logs.RollingIntervalDay)
// Security
logs.AddSensitiveKey("password")
logs.AddSensitiveKey("token")
logs.AddSensitiveKey("secret")
logs.AddSensitiveKey("apiKey")
logs.AddSensitiveKey("creditCard")
// Performance
logs.SetDuplicateSuppressionWindow(10000)
// Disable console in production
logs.SetConsoleEnabled(false)
// Use environment variable for project token
logs.SetProjectToken(os.Getenv("BYTEHIDE_LOGS_TOKEN"))
}import (
"os"
logs "github.com/bytehide/bytehide-logs-go"
)
func initializeProductionLogger() {
// Log levels
logs.SetMinimumLevel(logs.LogLevelWarn)
// File logging
logs.SetPersist(true)
logs.SetFilePath("logs/production.log")
logs.SetRollingInterval(logs.RollingIntervalDay)
// Security
logs.AddSensitiveKey("password")
logs.AddSensitiveKey("token")
logs.AddSensitiveKey("secret")
logs.AddSensitiveKey("apiKey")
logs.AddSensitiveKey("creditCard")
// Performance
logs.SetDuplicateSuppressionWindow(10000)
// Disable console in production
logs.SetConsoleEnabled(false)
// Use environment variable for project token
logs.SetProjectToken(os.Getenv("BYTEHIDE_LOGS_TOKEN"))
}Step 6: View Your Logs
After your application runs, you can view logs in multiple places:
Console Output (Development)
CODE
[2024-01-15 10:30:15] [Info] Application started successfully!
[2024-01-15 10:30:15] [Info] Processing order { orderId: "ORD-001", customerId: "CUST-123" }
[2024-01-15 10:30:16] [Info] Order processed successfully { orderId: "ORD-001", processingTime: "1.2s" }[2024-01-15 10:30:15] [Info] Application started successfully!
[2024-01-15 10:30:15] [Info] Processing order { orderId: "ORD-001", customerId: "CUST-123" }
[2024-01-15 10:30:16] [Info] Order processed successfully { orderId: "ORD-001", processingTime: "1.2s" }Log Files
Check your configured log file path (e.g., logs/app.log):
CODE
2024-01-15 10:30:15.123 [INFO] Application started successfully!
2024-01-15 10:30:15.456 [INFO] Processing order orderId=ORD-001 customerId=CUST-123
2024-01-15 10:30:16.789 [INFO] Order processed successfully orderId=ORD-001 processingTime=1.2s2024-01-15 10:30:15.123 [INFO] Application started successfully!
2024-01-15 10:30:15.456 [INFO] Processing order orderId=ORD-001 customerId=CUST-123
2024-01-15 10:30:16.789 [INFO] Order processed successfully orderId=ORD-001 processingTime=1.2sByteHide Web Panel
- Log in to ByteHide Cloud
- Select your Logs project
- View real-time logs, search, filter, and analyze
Common Patterns
Error Handling
Go
import "uuid"
func (api *ApiHandler) ProcessRequest(request *Request) *ApiResponse {
correlationId := uuid.New().String()
logs.WithCorrelationID(correlationId).
WithContext("requestId", request.ID).
WithContext("type", request.Type).
Info("Request received")
result, err := processBusinessLogic(request)
if err != nil {
if isValidationError(err) {
logs.WithCorrelationID(correlationId).
WithContext("requestId", request.ID).
WithException(err).
Warn("Request validation failed")
return ApiResponse{Status: "BadRequest", Message: err.Error()}
}
logs.WithCorrelationID(correlationId).
WithException(err).
Error("Request processing failed", err)
return ApiResponse{Status: "InternalError"}
}
logs.WithCorrelationID(correlationId).
WithContext("requestId", request.ID).
WithContext("resultCount", len(result.Items)).
Info("Request processed successfully")
return ApiResponse{Status: "Success", Data: result}
}import "uuid"
func (api *ApiHandler) ProcessRequest(request *Request) *ApiResponse {
correlationId := uuid.New().String()
logs.WithCorrelationID(correlationId).
WithContext("requestId", request.ID).
WithContext("type", request.Type).
Info("Request received")
result, err := processBusinessLogic(request)
if err != nil {
if isValidationError(err) {
logs.WithCorrelationID(correlationId).
WithContext("requestId", request.ID).
WithException(err).
Warn("Request validation failed")
return ApiResponse{Status: "BadRequest", Message: err.Error()}
}
logs.WithCorrelationID(correlationId).
WithException(err).
Error("Request processing failed", err)
return ApiResponse{Status: "InternalError"}
}
logs.WithCorrelationID(correlationId).
WithContext("requestId", request.ID).
WithContext("resultCount", len(result.Items)).
Info("Request processed successfully")
return ApiResponse{Status: "Success", Data: result}
}Performance Monitoring
Go
import "time"
func (repo *ProductRepository) GetProducts(categoryId int) ([]Product, error) {
startTime := time.Now()
products, err := repo.database.GetByCategory(categoryId)
elapsed := time.Since(startTime).Milliseconds()
if err != nil {
logs.WithContext("categoryId", categoryId).
WithContext("elapsedMs", elapsed).
WithException(err).
Error("Failed to retrieve products", err)
return nil, err
}
logs.WithContext("categoryId", categoryId).
WithContext("productCount", len(products)).
WithContext("elapsedMs", elapsed).
Info("Products retrieved")
return products, nil
}import "time"
func (repo *ProductRepository) GetProducts(categoryId int) ([]Product, error) {
startTime := time.Now()
products, err := repo.database.GetByCategory(categoryId)
elapsed := time.Since(startTime).Milliseconds()
if err != nil {
logs.WithContext("categoryId", categoryId).
WithContext("elapsedMs", elapsed).
WithException(err).
Error("Failed to retrieve products", err)
return nil, err
}
logs.WithContext("categoryId", categoryId).
WithContext("productCount", len(products)).
WithContext("elapsedMs", elapsed).
Info("Products retrieved")
return products, nil
}Next Steps
Now that you have basic logging working: