DevOps help for Cloud Platform Engineers
  • Welcome!
  • Quick Start Guide
  • About Me
  • CV
  • 🧠DevOps & SRE Foundations
    • DevOps Overview
      • Engineering Fundamentals
      • Implementing DevOps Strategy
      • DevOps Readiness Assessment
      • Lifecycle Management
      • The 12 Factor App
      • Design for Self Healing
      • Incident Management Best Practices (2025)
    • SRE Fundamentals
      • Toil Reduction
      • System Simplicity
      • Real-world Scenarios
        • AWS VM Log Monitoring API
    • Agile Development
      • Team Agreements
        • Definition of Done
        • Definition of Ready
        • Team Manifesto
        • Working Agreement
    • Industry Scenarios
      • Finance and Banking
      • Public Sector (UK/EU)
      • Energy Sector Edge Computing
  • DevOps Practices
    • Platform Engineering
    • FinOps
    • Observability
      • Modern Practices
  • 🚀Modern DevOps Practices
    • Infrastructure Testing
    • Modern Development
    • Database DevOps
  • 🛠️Infrastructure as Code (IaC)
    • Terraform
      • Getting Started - Installation and initial setup [BEGINNER]
      • Cloud Integrations - Provider-specific implementations
        • Azure Scenarios
        • AWS Scenarios
        • GCP Scenarios
      • Testing and Validation - Ensuring infrastructure quality
        • Unit Testing
        • Integration Testing
        • End-to-End Testing
        • Terratest Guide
      • Best Practices - Production-ready implementation strategies
        • State Management
        • Security
        • Code Organization
        • Performance
      • Tools & Utilities - Enhancing the Terraform workflow
        • Terraform Docs
        • TFLint
        • Checkov
        • Terrascan
      • CI/CD Integration - Automating infrastructure deployment
        • GitHub Actions - GitHub-based automation workflows
        • Azure Pipelines - Azure DevOps integration
        • GitLab CI - GitLab-based deployment pipelines
    • Bicep
      • Getting Started - First steps with Bicep [BEGINNER]
      • Template Specs
      • Best Practices - Guidelines for effective Bicep implementations
      • Modules - Building reusable components [INTERMEDIATE]
      • Examples - Sample implementations for common scenarios
      • Advanced Features
      • CI/CD Integration - Automating Bicep deployments
        • GitHub Actions
        • Azure Pipelines
  • 💰Cost Management & FinOps
    • Cloud Cost Optimization
  • 🐳Containers & Orchestration
    • Containerization Overview
    • Docker
      • Dockerfile Best Practices
      • Docker Compose
    • Kubernetes
      • CLI Tools - Essential command-line utilities
        • Kubectl
        • Kubens
        • Kubectx
      • Core Concepts
      • Components
      • Best Practices
        • Pod Security
        • Security Monitoring
        • Resource Limits
      • Advanced Features - Beyond the basics [ADVANCED]
        • Service Mesh
        • Ingress Controllers
          • NGINX
          • Traefik
          • Kong
          • Gloo Edge
      • Troubleshooting - Diagnosing and resolving common issues
        • Pod Troubleshooting Commands
      • Enterprise Architecture
      • Health Management
      • Security & Compliance
      • Virtual Clusters
    • OpenShift
  • Service Mesh & Networking
    • Service Mesh Implementation
  • Architecture Patterns
    • Data Mesh
    • Multi-Cloud Networking
    • Disaster Recovery
    • Chaos Engineering
  • Edge Computing
    • Implementation Guide
    • Serverless Edge
    • IoT Edge Patterns
    • Real-Time Processing
    • Edge AI/ML
    • Security Hardening
    • Observability Patterns
    • Network Optimization
    • Storage Patterns
  • 🔄CI/CD & GitOps
    • CI/CD Overview
    • Continuous Integration
    • Continuous Delivery
      • Deployment Strategies
      • Secrets Management
      • Blue-Green Deployments
      • Deployment Metrics
      • Progressive Delivery
      • Release Management for DevOps/SRE (2025)
    • CI/CD Platforms - Tool selection and implementation
      • Azure DevOps
        • Pipelines
          • Stages
          • Jobs
          • Steps
          • Templates - Reusable pipeline components
          • Extends
          • Service Connections - External service authentication
          • Best Practices for 2025
          • Agents and Runners
          • Third-Party Integrations
          • Azure DevOps CLI
        • Boards & Work Items
      • GitHub Actions
      • GitLab
        • GitLab Runner
        • Real-life scenarios
        • Installation guides
        • Pros and Cons
        • Comparison with alternatives
    • GitOps
      • Modern GitOps Practices
      • GitOps Patterns for Multi-Cloud (2025)
      • Flux
        • Overview
        • Progressive Delivery
        • Use GitOps with Flux, GitHub and AKS
  • Source Control
    • Source Control Overview
    • Git Branching Strategies
    • Component Versioning
    • Kubernetes Manifest Versioning
    • GitLab
    • Creating a Fork
    • Naming Branches
    • Pull Requests
    • Integrating LLMs into Source Control Workflows
  • ☁️Cloud Platforms
    • Cloud Strategy
    • Azure
      • Best Practices
      • Landing Zones
      • Services
      • Monitoring
      • Administration Tools - Platform management interfaces
        • Azure PowerShell
        • Azure CLI
      • Tips & Tricks
    • AWS
      • Authentication
      • Best Practices
      • Tips & Tricks
    • Google Cloud
      • Services
    • Private Cloud
  • 🔐Security & Compliance
    • DevSecOps Overview
    • DevSecOps Pipeline Security
    • DevSecOps
      • Real-life Examples
      • Scanning & Protection - Automated security tooling
        • Dependency Scanning
        • Credential Scanning
        • Container Security Scanning
        • Static Code Analysis
          • Best Practices
          • Tool Integration Guide
          • Pipeline Configuration
      • CI/CD Security
      • Secrets Rotation
    • Supply Chain Security
      • SLSA Framework
      • Binary Authorization
      • Artifact Signing
    • Security Best Practices
      • Threat Modeling
      • Kubernetes Security
    • SecOps
    • Zero Trust Model
    • Cloud Compliance
      • ISO/IEC 27001:2022
      • ISO 22301:2019
      • PCI DSS
      • CSA STAR
    • Security Frameworks
    • SIEM and SOAR
  • Security Architecture
    • Zero Trust Implementation
      • Identity Management
      • Network Security
      • Access Control
  • 🔍Observability & Monitoring
    • Observability Fundamentals
    • Logging
    • Metrics
    • Tracing
    • Dashboards
    • SLOs and SLAs
    • Observability as Code
    • Pipeline Observability
  • 🧪Testing Strategies
    • Testing Overview
    • Modern Testing Approaches
    • End-to-End Testing
    • Unit Testing
    • Performance Testing
      • Load Testing
    • Fault Injection Testing
    • Integration Testing
    • Smoke Testing
  • 🤖AI Integration
    • AIops Overview
      • Workflow Automation
      • Predictive Analytics
      • Code Quality
  • 🧠AI & LLM Integration
    • Overview
    • Claude
      • Installation Guide
      • Project Guides
      • MCP Server Setup
      • LLM Comparison
    • Ollama
      • Installation Guide
      • Configuration
      • Models and Fine-tuning
      • DevOps Usage
      • Docker Setup
      • GPU Setup
      • Open WebUI
    • Copilot
      • Installation Guide
      • VS Code Integration
      • CLI Usage
    • Gemini
      • Installation Guides - Platform-specific setup
        • Linux Installation
        • WSL Installation
        • NixOS Installation
      • Gemini 2.5 Features
      • Roles and Agents
      • NotebookML Guide
      • Cloud Infrastructure Deployment
      • Summary
  • 💻Development Environment
    • Tools Overview
    • DevOps Tools
    • Operating Systems - Development platforms
      • NixOS
        • Installation
        • Nix Language Guide
        • DevEnv with Nix
        • Cloud Deployments
      • WSL2
        • Distributions
        • Terminal Setup
    • Editor Environments
    • CLI Tools
      • Azure CLI
      • PowerShell
      • Linux Commands
      • YAML Tools
  • 📚Programming Languages
    • Python
    • Go
    • JavaScript/TypeScript
    • Java
    • Rust
  • 📖Documentation Best Practices
    • Documentation Strategy
    • Project Documentation
    • Release Notes
    • Static Sites
    • Documentation Templates
    • Real-World Examples
  • 📋Reference Materials
    • Glossary
    • Tool Comparison
    • Recommended Reading
    • Troubleshooting Guide
  • Platform Engineering
    • Implementation Guide
  • FinOps
    • Implementation Guide
  • AIOps
    • LLMOps Guide
  • Development Setup
    • Development Setup
Powered by GitBook
On this page
  • Scenario Description
  • Problem Statement
  • Solution: Log Exposition API in Golang
  • Implementation
  • Complete Golang API Code
  • Configuration File Example
  • Deployment Guide
  • Prerequisites
  • Building the API
  • Deploying to AWS EC2
  • Security Configuration
  • Integration with Monitoring Systems
  • Prometheus Integration
  • Grafana Dashboard
  • API Usage Examples
  • Troubleshooting
  • Common Issues
  • Future Enhancements
Edit on GitHub
  1. DevOps & SRE Foundations
  2. SRE Fundamentals
  3. Real-world Scenarios

AWS VM Log Monitoring API

Scenario Description

Your team operates a critical service running on EC2 instances in AWS, but your current monitoring infrastructure lacks visibility into application-specific logs. The traditional approaches of installing agents or shipping logs aren't feasible due to security restrictions. You need a lightweight solution that can expose application logs through a secure API to integrate with your existing monitoring stack.

Problem Statement

  • Application logs are stored locally on EC2 instances

  • Security policies restrict installing third-party agents

  • Need real-time access to logs for monitoring and alerting

  • Solution must be lightweight and secure

  • Must integrate with existing monitoring tools (Prometheus, Grafana, etc.)

Solution: Log Exposition API in Golang

We'll create a lightweight HTTP API server in Golang that:

  1. Reads application logs from configurable local paths

  2. Exposes the logs via secure HTTP endpoints

  3. Provides filtering capabilities

  4. Includes authentication

  5. Offers metrics collection points for Prometheus

Implementation

Complete Golang API Code

Here's the complete implementation of our log exposition API:

// File: logapi/main.go
package main

import (
	"bufio"
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"time"

	"github.com/gorilla/mux"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

// Configuration holds application settings
type Configuration struct {
	LogPaths     []string          `json:"log_paths"`
	APIPort      int               `json:"api_port"`
	APIToken     string            `json:"api_token"`
	MaxLogSize   int               `json:"max_log_size"`
	MetricsPort  int               `json:"metrics_port"`
	AlertKeywords map[string]string `json:"alert_keywords"`
}

// LogEntry represents a single log entry
type LogEntry struct {
	Timestamp time.Time `json:"timestamp"`
	File      string    `json:"file"`
	Line      string    `json:"line"`
	Level     string    `json:"level,omitempty"`
}

var (
	config         Configuration
	configPath     string
	logsMutex      sync.RWMutex
	recentLogs     []LogEntry
	
	// Prometheus metrics
	logsReadTotal = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "logapi_logs_read_total",
			Help: "Total number of log entries processed",
		},
		[]string{"file", "level"},
	)
	
	apiRequestsTotal = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "logapi_requests_total",
			Help: "Total number of API requests",
		},
		[]string{"endpoint", "status"},
	)
	
	errorLogsTotal = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "logapi_error_logs_total",
			Help: "Total number of error logs detected",
		},
		[]string{"file", "keyword"},
	)
)

func init() {
	// Register prometheus metrics
	prometheus.MustRegister(logsReadTotal)
	prometheus.MustRegister(apiRequestsTotal)
	prometheus.MustRegister(errorLogsTotal)
	
	// Parse command line flags
	flag.StringVar(&configPath, "config", "/etc/logapi/config.json", "Path to configuration file")
	flag.Parse()
}

func main() {
	// Load configuration
	if err := loadConfig(); err != nil {
		log.Fatalf("Failed to load configuration: %v", err)
	}
	
	// Initialize log buffer
	recentLogs = make([]LogEntry, 0, config.MaxLogSize)
	
	// Start log reader goroutines
	for _, path := range config.LogPaths {
		go monitorLogs(path)
	}
	
	// Setup API router
	router := mux.NewRouter()
	router.Use(authMiddleware)
	router.HandleFunc("/logs", getLogsHandler).Methods("GET")
	router.HandleFunc("/logs/{file}", getFileLogsHandler).Methods("GET")
	router.HandleFunc("/health", healthCheckHandler).Methods("GET")
	
	// Setup metrics server on separate port
	metricsRouter := http.NewServeMux()
	metricsRouter.Handle("/metrics", promhttp.Handler())
	
	// Start servers
	go func() {
		log.Printf("Starting metrics server on :%d", config.MetricsPort)
		if err := http.ListenAndServe(fmt.Sprintf(":%d", config.MetricsPort), metricsRouter); err != nil {
			log.Fatalf("Metrics server failed: %v", err)
		}
	}()
	
	log.Printf("Starting API server on :%d", config.APIPort)
	if err := http.ListenAndServe(fmt.Sprintf(":%d", config.APIPort), router); err != nil {
		log.Fatalf("API server failed: %v", err)
	}
}

func loadConfig() error {
	file, err := os.Open(configPath)
	if err != nil {
		return err
	}
	defer file.Close()
	
	decoder := json.NewDecoder(file)
	if err := decoder.Decode(&config); err != nil {
		return err
	}
	
	// Set defaults if not provided
	if config.APIPort == 0 {
		config.APIPort = 8080
	}
	if config.MetricsPort == 0 {
		config.MetricsPort = 9090
	}
	if config.MaxLogSize == 0 {
		config.MaxLogSize = 10000
	}
	
	return nil
}

func monitorLogs(logPath string) {
	filename := filepath.Base(logPath)
	log.Printf("Starting to monitor log file: %s", logPath)
	
	for {
		file, err := os.Open(logPath)
		if err != nil {
			log.Printf("Error opening log file %s: %v", logPath, err)
			time.Sleep(5 * time.Second)
			continue
		}
		
		// Seek to end of file for new logs only
		file.Seek(0, io.SeekEnd)
		
		scanner := bufio.NewScanner(file)
		for scanner.Scan() {
			line := scanner.Text()
			addLogEntry(filename, line)
		}
		
		if err := scanner.Err(); err != nil {
			log.Printf("Error reading log file %s: %v", logPath, err)
		}
		
		file.Close()
		time.Sleep(1 * time.Second)
	}
}

func addLogEntry(filename, line string) {
	// Simple log level detection
	level := "info"
	lowerLine := strings.ToLower(line)
	
	if strings.Contains(lowerLine, "error") {
		level = "error"
	} else if strings.Contains(lowerLine, "warn") {
		level = "warning"
	} else if strings.Contains(lowerLine, "debug") {
		level = "debug"
	}
	
	// Check for alert keywords
	for keyword, severity := range config.AlertKeywords {
		if strings.Contains(lowerLine, strings.ToLower(keyword)) {
			errorLogsTotal.WithLabelValues(filename, keyword).Inc()
			// In a real implementation, you might want to send alerts here
		}
	}
	
	entry := LogEntry{
		Timestamp: time.Now(),
		File:      filename,
		Line:      line,
		Level:     level,
	}
	
	logsMutex.Lock()
	defer logsMutex.Unlock()
	
	// Add to circular buffer, remove oldest if full
	if len(recentLogs) >= config.MaxLogSize {
		recentLogs = recentLogs[1:]
	}
	recentLogs = append(recentLogs, entry)
	
	// Update metrics
	logsReadTotal.WithLabelValues(filename, level).Inc()
}

func authMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Skip auth for health check
		if r.URL.Path == "/health" {
			next.ServeHTTP(w, r)
			return
		}
		
		token := r.Header.Get("X-API-Token")
		if token != config.APIToken {
			apiRequestsTotal.WithLabelValues(r.URL.Path, "401").Inc()
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}
		
		next.ServeHTTP(w, r)
	})
}

func getLogsHandler(w http.ResponseWriter, r *http.Request) {
	level := r.URL.Query().Get("level")
	limit := 100 // Default limit
	
	logsMutex.RLock()
	defer logsMutex.RUnlock()
	
	var filteredLogs []LogEntry
	
	// Apply filters
	for i := len(recentLogs) - 1; i >= 0 && len(filteredLogs) < limit; i-- {
		entry := recentLogs[i]
		if level == "" || entry.Level == level {
			filteredLogs = append(filteredLogs, entry)
		}
	}
	
	apiRequestsTotal.WithLabelValues("/logs", "200").Inc()
	json.NewEncoder(w).Encode(filteredLogs)
}

func getFileLogsHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	filename := vars["file"]
	level := r.URL.Query().Get("level")
	limit := 100 // Default limit
	
	logsMutex.RLock()
	defer logsMutex.RUnlock()
	
	var filteredLogs []LogEntry
	
	// Apply filters
	for i := len(recentLogs) - 1; i >= 0 && len(filteredLogs) < limit; i-- {
		entry := recentLogs[i]
		if entry.File == filename && (level == "" || entry.Level == level) {
			filteredLogs = append(filteredLogs, entry)
		}
	}
	
	apiRequestsTotal.WithLabelValues("/logs/"+filename, "200").Inc()
	json.NewEncoder(w).Encode(filteredLogs)
}

func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
	apiRequestsTotal.WithLabelValues("/health", "200").Inc()
	w.Write([]byte("OK"))
}

Configuration File Example

{
  "log_paths": [
    "/var/log/application/app.log",
    "/var/log/application/error.log"
  ],
  "api_port": 8080,
  "metrics_port": 9090,
  "api_token": "your-secure-api-token-here",
  "max_log_size": 10000,
  "alert_keywords": {
    "exception": "critical",
    "crashed": "critical",
    "timeout": "warning"
  }
}

Deployment Guide

Prerequisites

  • Go 1.18 or higher

  • AWS EC2 instance with your application running

  • Access to install and run services on the EC2 instance

Building the API

  1. Create a project directory on your development machine:

mkdir -p ~/projects/logapi
cd ~/projects/logapi
  1. Initialize the Go module:

go mod init logapi
  1. Create the main.go file with the code provided above

  2. Install dependencies:

go get github.com/gorilla/mux
go get github.com/prometheus/client_golang/prometheus
go get github.com/prometheus/client_golang/prometheus/promhttp
  1. Build the binary:

go build -o logapi main.go

Deploying to AWS EC2

  1. Create a configuration directory and file on the EC2 instance:

sudo mkdir -p /etc/logapi
sudo vim /etc/logapi/config.json
  1. Copy and modify the example configuration file provided above to match your application's log paths.

  2. Copy the compiled binary to the EC2 instance:

scp -i your-key.pem logapi ec2-user@your-ec2-instance:/tmp/
  1. Set up the service on the EC2 instance:

sudo mv /tmp/logapi /usr/local/bin/
sudo chmod +x /usr/local/bin/logapi
  1. Create a systemd service file:

sudo tee /etc/systemd/system/logapi.service > /dev/null << 'EOF'
[Unit]
Description=Log Exposition API
After=network.target

[Service]
ExecStart=/usr/local/bin/logapi --config=/etc/logapi/config.json
Restart=always
User=root
Group=root
Environment=PATH=/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
WorkingDirectory=/usr/local/bin

[Install]
WantedBy=multi-user.target
EOF
  1. Start and enable the service:

sudo systemctl daemon-reload
sudo systemctl enable logapi
sudo systemctl start logapi
  1. Verify the service is running:

sudo systemctl status logapi

Security Configuration

To secure the API:

  1. Configure a secure API token in the config.json file

  2. Set up an AWS security group to only allow traffic from your monitoring systems

  3. Consider setting up an HTTPS proxy with Nginx or similar if needed

Integration with Monitoring Systems

Prometheus Integration

Add this configuration to your Prometheus scrape configs:

scrape_configs:
  - job_name: 'logapi'
    scrape_interval: 15s
    static_configs:
      - targets: ['your-ec2-instance:9090']

Grafana Dashboard

Create a dashboard to visualize the metrics:

  1. Add a Prometheus data source in Grafana

  2. Create panels for metrics like:

    • logapi_logs_read_total (by file, by level)

    • logapi_error_logs_total (by keyword)

    • logapi_requests_total (by endpoint, status)

API Usage Examples

To fetch logs from your monitoring system:

# Get recent logs
curl -H "X-API-Token: your-secure-api-token-here" http://your-ec2-instance:8080/logs

# Get only error logs
curl -H "X-API-Token: your-secure-api-token-here" http://your-ec2-instance:8080/logs?level=error

# Get logs from a specific file
curl -H "X-API-Token: your-secure-api-token-here" http://your-ec2-instance:8080/logs/app.log

Troubleshooting

Common Issues

  1. API returns "Unauthorized":

    • Verify the API token in your request matches the one in config.json

  2. No logs appearing:

    • Check that the log paths in config.json are correct

    • Verify the service has permission to read those log files

  3. Service won't start:

    • Check logs with sudo journalctl -u logapi

    • Verify the logapi binary has execution permissions

  4. High CPU usage:

    • Increase the polling interval in the monitorLogs function

    • Consider reducing the number of monitored log files

Future Enhancements

  1. Add support for TLS/HTTPS

  2. Implement log rotation handling

  3. Add support for structured log formats (JSON, etc.)

  4. Implement alerting capabilities directly from the API

  5. Add support for distributed log collection across multiple instances

PreviousReal-world ScenariosNextAgile Development

Last updated 2 days ago

🧠