Documentation
¶
Index ¶
- func ActiveEventFromContext(ctx context.Context) string
- func IsFailureSeverity(s Severity) bool
- func WithActiveEvent(ctx context.Context, eventID string) context.Context
- func WithCollection(ctx context.Context, c *Collection) context.Context
- type Actor
- type Agent
- type Collection
- func (c *Collection) AddEvent(event Event)
- func (c *Collection) Commit()
- func (c *Collection) SetActor(actor *Actor)
- func (c *Collection) SetRequest(req *Request)
- func (c *Collection) SetRequestFromHTTP(r *http.Request, comm CommunicationProto, status int)
- func (c *Collection) StartEvent(name string, eventType EventType, severity Severity) *EventBuilder
- type CommunicationProto
- type Environment
- type Event
- type EventBuilder
- func (eb *EventBuilder) AddError(code, message string, stack *string) *EventBuilder
- func (eb *EventBuilder) End()
- func (eb *EventBuilder) Fail() *EventBuilder
- func (eb *EventBuilder) Succeed() *EventBuilder
- func (eb *EventBuilder) WithMessage(msg string) *EventBuilder
- func (eb *EventBuilder) WithMetadata(metadata map[string]any) *EventBuilder
- func (eb *EventBuilder) WithParent(parentID string) *EventBuilder
- type EventError
- type EventType
- type LogSchema
- type Options
- type Request
- type Service
- type Severity
- type Shipping
- type ShippingStats
- type Status
- type TimeInfo
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ActiveEventFromContext ¶ added in v0.0.2
ActiveEventFromContext recupera o ID do evento pai do contexto.
func IsFailureSeverity ¶ added in v1.1.0
IsFailureSeverity informa se a severidade denota falha (ERROR ou acima).
func WithActiveEvent ¶ added in v0.0.2
WithActiveEvent associa um ID de evento ao contexto.
func WithCollection ¶
func WithCollection(ctx context.Context, c *Collection) context.Context
WithCollection injeta uma instância de *Collection no contexto fornecido.
Types ¶
type Agent ¶
type Agent struct {
Service Service
Env Environment
SchemaVersion string
Shipping *Shipping
}
func NewAgent ¶
func NewAgent(service Service, env Environment, schemaVersion string, processLog func(LogSchema) error) *Agent
NewAgent inicializa o Agent de observabilidade. O parâmetro processLog é uma função opcional de callback para processamento dos logs estruturados. Se processLog for nil, os logs serão silenciosamente descartados da memória.
func NewAgentWithOptions ¶ added in v1.1.0
func NewAgentWithOptions(service Service, env Environment, schemaVersion string, processLog func(LogSchema) error, opts Options) *Agent
NewAgentWithOptions inicializa o Agent de observabilidade com opções extras. Ver NewAgent para o comportamento padrão.
func (*Agent) Close ¶
func (a *Agent) Close()
Close encerra as goroutines do Shipping de forma limpa, garantindo o processamento de logs remanescentes.
func (*Agent) NewCollection ¶
func (a *Agent) NewCollection(tracingID string) *Collection
NewCollection cria uma nova instância de Collection associada a este Agent para rastrear uma nova trace/requisição.
func (*Agent) Stats ¶ added in v1.1.0
func (a *Agent) Stats() ShippingStats
Stats é atalho para Agent.Shipping.Stats().
type Collection ¶
type Collection struct {
// contains filtered or unexported fields
}
func FromContext ¶
func FromContext(ctx context.Context) *Collection
FromContext recupera a instância de *Collection do contexto. Retorna nil se não estiver presente.
func NewCollection ¶
func NewCollection(agent *Agent, tracingID string) *Collection
NewCollection inicializa uma nova Collection vinculada ao Agent.
func (*Collection) AddEvent ¶
func (c *Collection) AddEvent(event Event)
AddEvent insere um evento completo de forma thread-safe.
O status é derivado da severidade quando não informado: eventos com severidade ERROR ou FATAL viram FAILURE. Um Status explícito é sempre respeitado.
func (*Collection) Commit ¶
func (c *Collection) Commit()
Commit finaliza a trace, calcula a duração e submete os dados para o Shipping do Agent. É idempotente: uma Collection representa um trace de uso único, e chamadas repetidas são no-op.
func (*Collection) SetActor ¶
func (c *Collection) SetActor(actor *Actor)
SetActor define informações do ator da requisição.
func (*Collection) SetRequest ¶
func (c *Collection) SetRequest(req *Request)
SetRequest define informações de requisição de forma thread-safe. É opcional: traces sem requisição (inicialização, jobs, workers, CLIs) podem nunca chamar este método — o campo "request" será omitido do JSON final. Passar nil também limpa uma requisição previamente definida.
func (*Collection) SetRequestFromHTTP ¶
func (c *Collection) SetRequestFromHTTP(r *http.Request, comm CommunicationProto, status int)
SetRequestFromHTTP preenche informações da requisição a partir de um *http.Request nativo. Se r for nil, a chamada é ignorada e o campo "request" permanece omitido.
func (*Collection) StartEvent ¶
func (c *Collection) StartEvent(name string, eventType EventType, severity Severity) *EventBuilder
StartEvent inicia a gravação de um evento. O evento será registrado no Collection chamando End().
type CommunicationProto ¶
type CommunicationProto string
const ( ProtoREST CommunicationProto = "REST" ProtoGRPC CommunicationProto = "gRPC" ProtoSOAP CommunicationProto = "SOAP" ProtoWebSocket CommunicationProto = "WebSocket" )
type Environment ¶
type Environment string
const ( Production Environment = "production" Staging Environment = "staging" Development Environment = "development" Testing Environment = "testing" )
Environment é uma string livre: as constantes abaixo são os valores convencionais, mas qualquer outro valor é aceito.
type Event ¶
type Event struct {
EventID string `json:"event_id"`
ParentEventID *string `json:"parent_event_id,omitempty"`
Name string `json:"name"`
Type EventType `json:"type"`
Status Status `json:"status"`
Severity Severity `json:"severity"`
Timestamp time.Time `json:"timestamp"`
DurationMs int `json:"duration_ms"`
Message string `json:"message"`
Metadata map[string]any `json:"metadata,omitempty"`
Errors []EventError `json:"errors,omitempty"`
Events []*Event `json:"events,omitempty"`
}
type EventBuilder ¶
type EventBuilder struct {
// contains filtered or unexported fields
}
EventBuilder auxilia desenvolvedores a construírem eventos com cálculo de tempo automático.
func StartEvent ¶ added in v0.0.2
func StartEvent(ctx context.Context, name string, eventType EventType, severity Severity) (context.Context, *EventBuilder)
StartEvent inicia a gravação de um evento usando context.Context. O evento herdará o ID do pai automaticamente.
func (*EventBuilder) AddError ¶
func (eb *EventBuilder) AddError(code, message string, stack *string) *EventBuilder
AddError adiciona um erro ocorrido durante a operação do evento, definindo o status do evento como FAILURE e elevando a severidade para no mínimo ERROR.
func (*EventBuilder) End ¶
func (eb *EventBuilder) End()
End calcula o tempo de duração final do evento e o adiciona à Collection.
func (*EventBuilder) Fail ¶ added in v1.1.0
func (eb *EventBuilder) Fail() *EventBuilder
Fail marca o evento como falho sem exigir um objeto de erro. Use quando a operação não teve sucesso mas não há código/mensagem de erro a registrar.
func (*EventBuilder) Succeed ¶ added in v1.1.0
func (eb *EventBuilder) Succeed() *EventBuilder
Succeed marca o evento como bem-sucedido explicitamente. Necessário apenas para manter SUCCESS em um evento com severidade ERROR ou FATAL, que de outro modo seria derivado como FAILURE em End().
func (*EventBuilder) WithMessage ¶
func (eb *EventBuilder) WithMessage(msg string) *EventBuilder
WithMessage adiciona uma mensagem explicativa ao evento.
func (*EventBuilder) WithMetadata ¶
func (eb *EventBuilder) WithMetadata(metadata map[string]any) *EventBuilder
WithMetadata injeta dados de contexto adicionais de forma flexível.
func (*EventBuilder) WithParent ¶
func (eb *EventBuilder) WithParent(parentID string) *EventBuilder
WithParent define o ID do evento pai para construir árvores/spans.
type EventError ¶
type LogSchema ¶
type LogSchema struct {
TracingID string `json:"tracing_id"`
Status Status `json:"status"`
Environment Environment `json:"environment"`
SchemaVersion string `json:"schema_version"`
Service Service `json:"service"`
// Request é opcional: traces que não nascem de uma requisição
// (inicialização do serviço, jobs, workers, CLIs) omitem o campo do JSON.
Request *Request `json:"request,omitempty"`
// Actor é opcional: omitido quando não há usuário ou serviço chamador.
Actor *Actor `json:"actor,omitempty"`
Time TimeInfo `json:"time"`
Events []*Event `json:"events"`
}
type Options ¶ added in v1.1.0
type Options struct {
// BufferSize é o tamanho da fila do Shipping. 0 usa o default (1000).
BufferSize int
// OnError é chamado quando ProcessLog devolve erro. Deve ser rápido e não
// entrar em pânico: roda no worker do Shipping.
OnError func(LogSchema, error)
}
Options configura comportamentos opcionais do Agent.
type Request ¶
type Request struct {
Communication CommunicationProto `json:"communication"`
Method string `json:"method,omitempty"`
Route string `json:"route,omitempty"`
Status int `json:"status"`
UserAgent string `json:"user_agent,omitempty"`
}
type Shipping ¶
type Shipping struct {
// contains filtered or unexported fields
}
func (*Shipping) Stats ¶ added in v1.1.0
func (s *Shipping) Stats() ShippingStats
Stats devolve um retrato dos contadores. Seguro para chamada concorrente.
type ShippingStats ¶ added in v1.1.0
type ShippingStats struct {
Shipped int64 // processados com sucesso
Failed int64 // ProcessLog devolveu erro
Dropped int64 // descartados por buffer cheio ou Shipping fechado
QueueDepth int // ocupação instantânea
QueueCapacity int
}
ShippingStats expõe contadores para métricas e diagnóstico.