logging

package
v0.1.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package logging 提供运行日志事件、控制台输出、请求跟踪与事件订阅

Index

Constants

View Source
const (
	SourceService = "service"
	SourceRequest = "request"
)

事件来源

View Source
const (
	EventMessage         = "runtime.message"
	EventRequestStarted  = "request.started"
	EventRequestProgress = "request.progress"
	EventRequestFinished = "request.finished"
)

稳定事件名

View Source
const (
	StateRunning   = "running"
	StateCompleted = "completed"
	StateToolCalls = "tool_calls"
	StateFailed    = "failed"
	StateCancelled = "cancelled"
)

请求状态

View Source
const FileMB = 10

FileMB 是单个日志文件的轮转大小

View Source
const StatusClientClosed = 499

StatusClientClosed 是客户端在请求完成前断开或请求被取消时记录的状态

Variables

View Source
var ErrCancelled = errors.New("request cancelled by the service administrator")

ErrCancelled 是管理端取消请求时请求 context 的取消原因

Functions

func ActiveCount

func ActiveCount() int

ActiveCount 返回活动生成请求数

func CancelRequest

func CancelRequest(id string) bool

CancelRequest 取消指定的活动请求

func Clear

func Clear()

Clear 清空保留的事件

func Debug

func Debug(source string, stage string, fields ...any)

Debug 记录调试事件

func Enabled

func Enabled(level slog.Level) bool

Enabled 报告该级别的事件是否会输出

func Error

func Error(source string, stage string, fields ...any)

Error 记录失败结果

func FormatDuration

func FormatDuration(duration time.Duration) string

FormatDuration 把时长四舍五入到毫秒,超过一分钟时到 100 毫秒

func FormatValue

func FormatValue(value any) string

FormatValue 把日志字段值格式化为短文本

func Info

func Info(source string, stage string, fields ...any)

Info 记录状态推进与完成结果

func Message

func Message(stage string, fields ...any) string

Message 把阶段名与键值对拼成“阶段 | 键=值”,键为空字符串时只写值

func ParseLevel

func ParseLevel(value string) (slog.Level, error)

ParseLevel 解析日志级别名称

func Publish

func Publish(event Event)

Publish 记录事件,低于最低级别的事件丢弃

func SanitizeError

func SanitizeError(message string) string

SanitizeError 去掉错误文本中 URL 的查询串,其中含会话参数

func SetFile added in v0.1.6

func SetFile(path string, enabled bool, maxTotalMB int) error

SetFile 开启或关闭日志文件:开启时控制台的每条事件同时以同一格式、不带颜色写入 path,单文件 FileMB 轮转,目录总量超过 maxTotalMB 时删除最旧的文件;路径与总量上限不变时沿用已有的轮转日志,关闭只关闭文件

func SetLevel

func SetLevel(level slog.Level)

SetLevel 修改最低输出级别

func SetSourceWidth

func SetSourceWidth(sources []string)

SetSourceWidth 按最长的账号 ID 设置控制台来源列宽度

func Setup

func Setup(options Options) error

Setup 按配置设置默认日志输出

func ShortID

func ShortID(id string) string

ShortID 返回请求 ID 在控制台显示的前 6 位

func Truncate

func Truncate(text string, limit int) string

Truncate 把文本截断到 limit 个字符

func Warn

func Warn(source string, stage string, fields ...any)

Warn 记录等待、切换与可恢复的失败

func Watch

func Watch(ctx context.Context)

Watch 每秒检查一次活动请求的等待状态,直到 ctx 结束

func WithRequest added in v0.1.7

func WithRequest(ctx context.Context, request *Request) context.Context

WithRequest 返回以 request 为请求跟踪的 context

Types

type Attempt

type Attempt struct {
	Account    string `json:"account"`
	Status     int    `json:"status"`
	Error      string `json:"error"`
	DurationMS int64  `json:"duration_ms"`
	// Hedge 表示首事件超时后发起的备用请求,Superseded 表示另一方先返回首事件后被取消
	Hedge      bool `json:"hedge,omitempty"`
	Superseded bool `json:"superseded,omitempty"`
}

Attempt 是一次未成功的上游尝试

type Event

type Event struct {
	Time    time.Time    `json:"time"`
	Level   string       `json:"level"`
	Source  string       `json:"source"`
	Message string       `json:"message"`
	Event   string       `json:"event"`
	Request *RequestInfo `json:"request,omitempty"`
}

Event 是一条运行日志事件

func History

func History() []Event

History 返回保留的最近事件

func Subscribe

func Subscribe(limit int) ([]Event, <-chan Event, func())

Subscribe 返回最近 limit 条事件与后续事件通道,通道在订阅者跟不上或取消时关闭

type Hub

type Hub struct {
	// contains filtered or unexported fields
}

Hub 保存最近事件,把新事件写到控制台并分发给订阅者

type Options

type Options struct {
	// Level 是最低输出级别,取值 debug、info、warn、error
	Level string
	// Format 是控制台格式,取值 text 或 json
	Format string
	// Writer 是控制台输出位置
	Writer io.Writer
}

Options 是日志输出配置

type Request

type Request struct {
	// contains filtered or unexported fields
}

Request 跟踪一次公开 API 请求从进入服务到结束的全部阶段

func FromContext

func FromContext(ctx context.Context) *Request

FromContext 返回 context 中的请求跟踪,没有时返回 nil,nil 上的方法不执行任何操作

func NewRequest

func NewRequest(parent context.Context, method string, path string, clientIP string) (*Request, context.Context)

NewRequest 登记一个进入服务的请求并返回带请求跟踪与取消函数的 context

func (*Request) AccountReady

func (r *Request) AccountReady(account string, model string)

AccountReady 记录已取得账号请求槽,开始一次上游尝试

func (*Request) AdoptHedge added in v0.1.7

func (r *Request) AdoptHedge(hedge *Request, reason string)

AdoptHedge 在备用请求取得输出时并入其跟踪:reason 非空时原请求的尝试以该原因记为被取代,账号、阶段、网络计数与首事件取备用请求的,此后备用请求跟踪的记录都写入原请求

func (*Request) AttemptFailed

func (r *Request) AttemptFailed(account string, status int, err error, retry bool)

AttemptFailed 记录一次失败的上游尝试,retry 表示随后换账号重试

func (*Request) Background

func (r *Request) Background(kind string)

Background 记录生成转入后台,服务开始轮询成品

func (*Request) Begin

func (r *Request) Begin(protocol string, model string, stream bool, messages int, tools int)

Begin 记录生成请求的协议、模型与输入概况并输出请求开始日志

func (*Request) Begun

func (r *Request) Begun() bool

Begun 报告请求是否为生成请求

func (*Request) Cancel

func (r *Request) Cancel()

Cancel 取消请求

func (*Request) Detach

func (r *Request) Detach(cancel context.CancelCauseFunc)

Detach 标记请求与客户端连接分离,客户端断开后请求按实际结果结束,管理端取消时以 cancel 取消分离后的 context

func (*Request) Fail

func (r *Request) Fail(status int, message string)

Fail 记录请求的最终失败状态与原因

func (*Request) Finish

func (r *Request) Finish(httpStatus int, clientGone bool) RequestInfo

Finish 按 HTTP 状态与记录的结果结束请求并输出结束日志,clientGone 表示客户端已断开

func (*Request) Hedge added in v0.1.7

func (r *Request) Hedge() *Request

Hedge 返回首事件备用请求的跟踪,日志沿用原请求 ID 并附带原请求的状态,账号、阶段与网络计数只记在备用请求自身

func (*Request) HedgeSuperseded added in v0.1.7

func (r *Request) HedgeSuperseded(account string, duration time.Duration, reason string)

HedgeSuperseded 记录原请求先返回首事件后被取消的备用请求

func (*Request) ID

func (r *Request) ID() string

ID 返回请求 ID

func (*Request) Progress added in v0.1.7

func (r *Request) Progress(level string, source string, message string, fields ...any)

Progress 以 source 输出一条带请求 ID 的进度日志

func (*Request) SetMedia

func (r *Request) SetMedia(count int)

SetMedia 记录本次请求上传的附件数

func (*Request) SetResponseID

func (r *Request) SetResponseID(responseID string)

SetResponseID 记录协议响应 ID

func (*Request) SetResult

func (r *Request) SetResult(providerModel string, conversationID string, finishReason string)

SetResult 记录上游实际模型、会话与结束原因

func (*Request) SetStage

func (r *Request) SetStage(stage string)

SetStage 记录当前阶段名,不输出日志,等待诊断与取消日志使用该名称

func (*Request) SetThinking added in v0.1.6

func (r *Request) SetThinking(level string)

SetThinking 记录按账号模型目录选定的网页思考强度

func (*Request) SetToolCalls

func (r *Request) SetToolCalls(count int)

SetToolCalls 记录本次输出的函数调用数

func (*Request) SetUsage

func (r *Request) SetUsage(input int, reasoning int, reply int)

SetUsage 记录 token 用量

func (*Request) Snapshot

func (r *Request) Snapshot() RequestInfo

Snapshot 返回请求当前信息

func (*Request) Stage

func (r *Request) Stage(stage string, fields ...any)

Stage 记录上游准备阶段,例如上传附件与接受条款

func (*Request) UpstreamEvent

func (r *Request) UpstreamEvent(kind string)

UpstreamEvent 记录解码出的语义事件,kind 为 thought、text、code、media 等

func (*Request) UpstreamHeartbeat

func (r *Request) UpstreamHeartbeat()

UpstreamHeartbeat 记录上游等待期间的心跳帧

func (*Request) UpstreamRead

func (r *Request) UpstreamRead(n int)

UpstreamRead 记录读取到的上游响应字节

func (*Request) UpstreamResponse

func (r *Request) UpstreamResponse(status int)

UpstreamResponse 记录生成请求取得响应头

type RequestInfo

type RequestInfo struct {
	ID             string    `json:"id"`
	ResponseID     string    `json:"response_id,omitempty"`
	ConversationID string    `json:"conversation_id,omitempty"`
	State          string    `json:"state"`
	Protocol       string    `json:"protocol,omitempty"`
	Method         string    `json:"method"`
	Path           string    `json:"path"`
	ClientIP       string    `json:"client_ip,omitempty"`
	Model          string    `json:"model,omitempty"`
	ProviderModel  string    `json:"provider_model,omitempty"`
	Thinking       string    `json:"thinking,omitempty"`
	Account        string    `json:"account,omitempty"`
	Stream         bool      `json:"stream"`
	Status         int       `json:"status,omitempty"`
	StartedAt      time.Time `json:"started_at"`
	DurationMS     int64     `json:"duration_ms"`
	QueueMS        int64     `json:"queue_ms,omitempty"`
	FirstEventMS   int64     `json:"first_event_ms,omitempty"`
	Stage          string    `json:"stage,omitempty"`
	Messages       int       `json:"messages,omitempty"`
	Media          int       `json:"media,omitempty"`
	Tools          int       `json:"tools,omitempty"`
	ToolCalls      int       `json:"tool_calls,omitempty"`
	FinishReason   string    `json:"finish_reason,omitempty"`
	Usage          *Usage    `json:"usage,omitempty"`
	Error          string    `json:"error,omitempty"`
	Attempts       []Attempt `json:"attempts,omitempty"`
	UpstreamBytes  int64     `json:"upstream_bytes,omitempty"`
	Heartbeats     int       `json:"heartbeats,omitempty"`
}

RequestInfo 是请求的阶段、账号、用量与结果

func ActiveRequests

func ActiveRequests() []RequestInfo

ActiveRequests 返回按开始时间排序的活动生成请求

func RecentRequests

func RecentRequests() []RequestInfo

RecentRequests 返回最近结束的生成请求,最新结束的在前

type Usage

type Usage struct {
	InputTokens     int `json:"input_tokens"`
	ReasoningTokens int `json:"reasoning_tokens"`
	ReplyTokens     int `json:"reply_tokens"`
	OutputTokens    int `json:"output_tokens"`
	TotalTokens     int `json:"total_tokens"`
}

Usage 是一次请求的 token 用量

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL