Site icon Efficient Coder

CozeLoop Go SDK – Turn Logs into Traceable Narratives in 10 Minutes

From Plain Logs to Traceable Narratives: A Complete Getting-Started Guide to the CozeLoop Go SDK

Backend engineers often face a dilemma: you need rich observability, but you don’t want to clutter business logic with logging boilerplate.
This guide shows you—in under ten minutes—how to turn every request and every prompt into a searchable, shareable, and replayable story using the CozeLoop Go SDK.
By the end, you will have installed the SDK, sent your first trace, templated your first prompt, and learned where to look if something breaks.


1. What Is CozeLoop, and Why Should You Care?

In one sentence:
CozeLoop is a unified platform that records request traces and large-model prompts so you can debug faster and collaborate better.

1.1 Traditional Logging vs. CozeLoop

Aspect Traditional Log Files CozeLoop Trace & Prompt Management
Data Structure Raw text Structured JSON with input, output, latency
Query Method grep, awk, or ELK stacks Point-and-click filters in a web UI
Traceability Manual request-id injection SDK auto-injects trace-id
Prompt Debugging Print prompt + completion to stdout Central prompt registry with variable substitution
Team Collaboration Copy-paste logs in chat Shared dashboards with role-based access

2. 10-Minute Quick-Start: From Zero to First Trace

2.1 Prerequisites

  • Go 1.18 or later
    Run go version and confirm you see go1.18 or higher.
  • Outbound HTTPS access
    The SDK pushes data to loop.coze.cn.

2.2 Install the SDK

Open a terminal in your project root:

go get github.com/coze-dev/cozeloop-go
go mod tidy

2.3 Create an OAuth App in the CozeLoop Console

  1. Navigate to https://loop.coze.cn/console/enterprise/personal/open/oauth/apps.
  2. Click Create App and choose Server-side application.
  3. Write down the following four values:
Environment Variable Example Value
COZELOOP_WORKSPACE_ID ws_abc123
COZELOOP_JWT_OAUTH_CLIENT_ID 12345
COZELOOP_JWT_OAUTH_PRIVATE_KEY Full PEM private key
COZELOOP_JWT_OAUTH_PUBLIC_KEY_ID k-1

Export them in your shell:

export COZELOOP_WORKSPACE_ID=ws_abc123
export COZELOOP_JWT_OAUTH_CLIENT_ID=12345
export COZELOOP_JWT_OAUTH_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n..."
export COZELOOP_JWT_OAUTH_PUBLIC_KEY_ID=k-1

2.4 Your First Trace in 15 Lines of Code

Create main.go:

package main

import (
    "context"
    "github.com/coze-dev/cozeloop-go/loop"
)

func main() {
    ctx := context.Background()

    // 1. Start a span
    ctx, span := loop.StartSpan(ctx, "root", "demo")

    // 2. Attach input and output
    span.SetInput(ctx, "Hello")
    span.SetOutput(ctx, "World")

    // 3. Finish and flush
    span.Finish(ctx)
    loop.Close(ctx)
}

Run it:

go run main.go

Refresh the Trace page in the CozeLoop console—you should see a new entry.


3. Managing Prompts Like Templates

3.1 Why Externalize Prompts?

  • Non-devs can tune copy without touching code.
  • Variable substitution keeps prompts DRY.
  • Versioning allows canary releases and rollbacks.

3.2 Upload a Prompt Template

In the console:

  1. Go to Prompt ManagementCreate Prompt.
  2. Set Prompt Key to greeting_prompt.
  3. Paste the template:
You are a {{role}}. Greet {{user}} in no more than 20 characters.
  1. Save and publish.

3.3 Fetch and Render the Prompt in Go

package main

import (
    "context"
    "fmt"
    "github.com/coze-dev/cozeloop-go/loop"
)

func main() {
    ctx := context.Background()

    prompt, err := loop.GetPrompt(ctx, loop.GetPromptParam{PromptKey: "greeting_prompt"})
    if err != nil {
        panic(err)
    }

    messages, err := loop.PromptFormat(ctx, prompt, map[string]any{
        "role": "Customer Service Bot",
        "user": "Alice",
    })
    if err != nil {
        panic(err)
    }

    fmt.Println(messages) // Output: You are a Customer Service Bot. Greet Alice in no more than 20 characters.
}

4. Frequently Asked Questions

4.1 Do I Have to Use Export for Secrets?

No.

  • Local dev: export is fastest.
  • Production containers: Inject via Kubernetes secrets or Vault; the SDK reads from os.Getenv.

4.2 The Private Key Is Huge—Any Tips?

Save it to key.pem, then:

b, _ := os.ReadFile("key.pem")
os.Setenv("COZELOOP_JWT_OAUTH_PRIVATE_KEY", string(b))

Add key.pem to .gitignore.

4.3 Can I Add Custom Tags?

Yes:

span.SetTag(ctx, "cost_ms", 123)

These tags appear as searchable fields in the UI.

4.4 Will This Hurt My QPS?

The SDK uses asynchronous batching with an internal buffer.
For extreme loads, increase the buffer size or enable the local-disk queue.

4.5 What About Sensitive Data?

  • Sanitize before SetInput / SetOutput.
  • Configure sampling in the console to keep only a fraction of traces.
  • On-prem deployments are available for compliance teams.

4.6 Must I Send Data to the Public Internet?

The default endpoint is public.
A private relay can be provided—contact CozeLoop support.


5. Building from Source and Contributing

If you want to submit a PR:

  1. Fork the repo on GitHub.
  2. Ensure Go ≥ 1.18.
  3. Install dependencies:
    go mod tidy
    
  4. Build:
    go build ./...
    
  5. Run tests:
    go test ./...
    
  6. Push your branch and open a pull request.

Typical review time: 1–2 business days.


6. Reporting Security Issues

Found a vulnerability? Do not open a public GitHub issue.
Use one of these private channels:


7. License

The project is released under the MIT License.
In plain English:

  • You may use, copy, modify, and distribute it.
  • You must retain the original copyright notice.
  • No warranty—use at your own risk.

Read the full text in the LICENSE file at the repository root.


8. Next Steps

You have already:

  • ✅ Installed the SDK
  • ✅ Sent your first trace
  • ✅ Externalized and rendered a prompt
  • ✅ Learned how to contribute safely

Suggested follow-ups:

  1. Auto-inject trace-id into your HTTP or gRPC middleware.
  2. Set up alerts—notify Feishu when error rate > 5 %.
  3. Run A/B prompts—deploy two prompt versions and compare via trace analytics.

Enjoy tracing, and feel free to open an issue if you get stuck!

Exit mobile version