# Beego

> Instrument Beego v2 Go applications with the Last9 Go Agent for automatic HTTP request tracing and metrics

Source: https://last9.io/docs/integrations/frameworks/go/beego/

Use the Last9 Go Agent to instrument your Beego v2 application with automatic tracing and metrics. The agent wraps the official OpenTelemetry Beego middleware under the hood — full OTel compliance with minimal code changes.

## Prerequisites

- Go 1.22 or higher
- Beego v2 (`github.com/beego/beego/v2`)
- Last9 account with OTLP credentials

## Installation

1. **Install the Last9 Go Agent**

   ```bash
   go get github.com/last9/go-agent
   ```

2. **Set Environment Variables**

   ```bash
   export OTEL_SERVICE_NAME="your-beego-service"
   export OTEL_EXPORTER_OTLP_ENDPOINT="$last9_otlp_endpoint"
   export OTEL_EXPORTER_OTLP_HEADERS="Authorization=$last9_otlp_auth_header"
   export OTEL_TRACES_SAMPLER="always_on"
   export OTEL_RESOURCE_ATTRIBUTES="deployment.environment=production"
   ```

3. **Instrument your application**

**New application**

   Replace `web.Run()` with the instrumented server — `beegoagent.New()` returns a `*web.HttpServer` with tracing middleware already attached:

   ```go
   package main

   import (
       "log"

       "github.com/beego/beego/v2/server/web"
       "github.com/last9/go-agent"
       beegoagent "github.com/last9/go-agent/instrumentation/beego"
   )

   func main() {
       if err := agent.Start(); err != nil {
           log.Fatalf("failed to start agent: %v", err)
       }
       defer agent.Shutdown()

       // Drop-in replacement — returns an instrumented *web.HttpServer
       app := beegoagent.New()

       web.Router("/", &IndexController{})
       web.Router("/users/:id", &UserController{})

       app.Run()
   }
   ```

**Existing application**

   Add the middleware to your existing Beego application:

   ```go
   package main

   import (
       "log"

       "github.com/beego/beego/v2/server/web"
       "github.com/last9/go-agent"
       beegoagent "github.com/last9/go-agent/instrumentation/beego"
   )

   func main() {
       if err := agent.Start(); err != nil {
           log.Fatalf("failed to start agent: %v", err)
       }
       defer agent.Shutdown()

       // Add tracing middleware to your existing app
       web.InsertFilter("*", web.BeforeRouter, beegoagent.Middleware())

       web.Router("/users/:id", &UserController{})
       web.Run()
   }
   ```

## Database Instrumentation

Use the agent's database integration for automatic SQL query tracing. Supported drivers: PostgreSQL, MySQL, SQLite.

```go
import (
    "database/sql"
    "log"

    "github.com/last9/go-agent/integrations/database"
)

var db *sql.DB

func init() {
    var err error
    db, err = database.Open(database.Config{
        DriverName:   "postgres",
        DSN:          "postgres://user:pass@localhost/mydb",
        DatabaseName: "mydb",
    })
    if err != nil {
        log.Fatal(err)
    }
}

// Use db normally — all queries are automatically traced
func (c *UserController) Get() {
    rows, err := db.QueryContext(c.Ctx.Request.Context(), "SELECT id, name FROM users WHERE id = ?", c.Ctx.Input.Param(":id"))
    // ...
}
```

The agent automatically extracts `server.address`, `server.port`, `db.user`, and `db.name` from the DSN and attaches them to every span.

## Redis Instrumentation

```go
import redisagent "github.com/last9/go-agent/integrations/redis"

// Drop-in replacement for redis.NewClient()
rdb := redisagent.NewClient(&redis.Options{
    Addr: "localhost:6379",
})

func (c *CacheController) Get() {
    val, err := rdb.Get(c.Ctx.Request.Context(), "key").Result()
    // ...
}
```

## HTTP Client Instrumentation

For outgoing requests with automatic `traceparent` propagation:

```go
import httpagent "github.com/last9/go-agent/integrations/http"

client := httpagent.NewClient(&http.Client{
    Timeout: 10 * time.Second,
})

func (c *ProxyController) Get() {
    req, _ := http.NewRequestWithContext(c.Ctx.Request.Context(), "GET", "https://upstream.example.com/api", nil)
    resp, err := client.Do(req)
    // ...
}
```

## What Gets Traced Automatically

| Signal  | What's captured                                                    |
| ------- | ------------------------------------------------------------------ |
| Traces  | Every HTTP request: method, route pattern, status code, latency    |
| Traces  | Database queries: SQL statement, db system, server address/port    |
| Traces  | Redis commands: command name, key                                  |
| Traces  | Outbound HTTP: method, URL, status code                            |
| Metrics | Runtime: memory, GC pause, goroutine count                         |
| Metrics | HTTP: request duration, request/response sizes, active connections |
| Metrics | Database: connection pool usage, idle, wait time                   |

## View Traces and Metrics

After running your application, navigate to [Trace Explorer](https://app.last9.io/traces) and [Metrics Explorer](https://app.last9.io/metrics) in Last9 to view your telemetry data.

---

## Troubleshooting

Please get in touch with us on [Discord](https://discord.com/invite/Q3p2EEucx9) or [Email](mailto:support@last9.io) if you have any questions.
