line

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: BSD-3-Clause Imports: 3 Imported by: ? 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.

README

Line

Go Reference

Line is a Go library for canonical log lines.

Canonical log lines (sometimes called "wide events") is a concept where instead of using every separate log statement as a separate line in the output, log information is collected through the call stack and logged only once as a single line.

Instead of using a certain logging solution, the package provides an abstraction over a provided logger to use canonical log lines with any implementation. As a convenience, while being dependency free, the library adds a function to wrap slog.Logger from the standard library for drop-in usage.

License

Unless otherwise noted, the source files are distributed under the BSD-3-Clause license.

Usage

Line represents a canonical log line stored in a context.Context.

  1. To create a Line in a context, use With.
  2. Line can be retrieved from a context via At.
  3. Use methods on a Line to add attributes. They are key/value pairs in a slice.
  4. When you are finished, use Record to log. It accepts a Liner interface.

That's it. A default Liner can be created with the Wrap function.

Examples

Simple

Code:

package main

import (
	"context"
	"fmt"
	"log/slog"

	"codeberg.org/shimeoki/line"
)

func main() {
	ctx := line.With(context.Background(), line.Warn)
	defer line.Record(ctx, line.Wrap(slog.Default()), "lined")

	line.At(ctx).
		Info("status", "line opened").
		Warn("important", "something is missing")

	line.At(ctx).Error("error", fmt.Errorf("an error happened"))
}

Output:

yyyy/mm/dd hh:mm:ss ERROR lined important="something is missing" error="an error happened"

Explanation:

  1. We use slog.Default(), so the format uses log package: date, time, level, message and the attributes.
  2. First we line status with Info level and important with Warn level. Because the quietness in the line is set to line.Warn, status is ignored in the end.
  3. Then we line error with error level. It's the highest level of the lined statements, so the severity in the Record call is line.Error.
HTTP middleware

Here is an example code snippet of real usage. lr in the parameter list is created manually with a logger of choice as the backing implementation. It's probably better to also pass the desired quietness.

func LoggingHandler(h http.Handler, lr line.Liner) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // statusWriter is defined earlier to simply intercept statusCode
		wrapped := &statusWriter{ResponseWriter: w, statusCode: http.StatusOK}

		ctx := line.With(r.Context(), line.Info)
		defer line.Record(ctx, lr, "handled http request")

		start := time.Now()
		h.ServeHTTP(wrapped, r.WithContext(ctx))

		ln := line.At(ctx).
			Info("api/method", r.Method).
			Info("api/spent", time.Since(start)).
			Info("api/url", r.URL.Path)

		if wrapped.statusCode >= 400 {
			ln.Error("api/status", wrapped.statusCode)
		} else {
			ln.Info("api/status", wrapped.statusCode)
		}
	})
}

Installation

The module requires at least Go 1.21.

go get codeberg.org/shimeoki/line

Documentation

Overview

Example
package main

import (
	"context"
	"fmt"
	"log/slog"

	"codeberg.org/shimeoki/line"
)

func main() {
	ctx := line.With(context.Background(), line.Warn)
	defer line.Record(ctx, line.Wrap(slog.Default()), "lined")

	line.At(ctx).
		Info("status", "line opened").
		Warn("important", "something is missing")

	line.At(ctx).Error("error", fmt.Errorf("an error happened"))
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Record

func Record(ctx context.Context, lr Liner, msg string) context.Context

Record retrieves a Line from ctx to log it in lr with the provided msg. It returns a context.Context without a Line.

If ctx doesn't have a Line, then the function call does nothing and returns the same context.

This function is safe to use by multiple goroutines.

func With

func With(ctx context.Context, quietness Level) context.Context

With returns a derived context.Context from ctx with a new Line and specified quietness. This Line is independent, but has copied attributes and severity from the Line in ctx (if there was one).

It is expected to also use Record in the same function where With was called, analogous to Open and Close.

Types

type Attr

type Attr struct {
	Key   string
	Value any
}

Attr is a Key/Value pair for an event in a Line.

func Any added in v0.2.0

func Any(key string, value any) Attr

Any returns a new Attr with the passed key and value.

type Level

type Level int

Level is either severity of an event or quietness (event threshold).

Severity is an overall importance of an event or a Line. Literally it means "the highest event level in the line". Higher value means higher event level, therefore higher severity. For example, if a Line has both Debug and Warn events, then the severity is Warn and cannot drop below Warn.

Quietness is a filter for events in a Line. Stored events should have severity equal to or greater than the quietness value. Therefore, resulting line cannot have severity less than the quietness. For example, with Warn quietness, Warn and Error events are stored, while Info and Debug are not.

Values of Level align with the values of slog.Level.

const (
	Debug Level = -4
	Info  Level = 0
	Warn  Level = 4
	Error Level = 8
)

type Line

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

Line is a struct for current canonical log line data. It's kept in a context.Context and can be retrieved using At. Line shouldn't be created manually, see With. Zero value is safe to use, but does nothing.

Though Line is used as a value (not passed around as a pointer), it should be treated as such, because of the shared state. In each derived context the state of a Line is shared between the functions to collect [Attr]s through the call stack.

Line is safe to use by multiple goroutines.

func At

func At(ctx context.Context) Line

At returns a Line from provided ctx.

If a Line wasn't found in ctx, then Line has a no-op state. In this state all method calls are skipped.

func (Line) Add

func (ln Line) Add(lvl Level, key string, value any) Line

Add calls Line.Append with lvl and a single Attr.

func (Line) Append added in v0.2.0

func (ln Line) Append(lvl Level, attrs ...Attr) Line

Append attrs with severity lvl to ln. Line is returned to allow method chaining. Append is skipped on empty attrs or no-op ln.

func (Line) Debug

func (ln Line) Debug(key string, value any) Line

Debug calls Line.Add with Debug as lvl.

func (Line) Error

func (ln Line) Error(key string, value any) Line

Error calls Line.Add with Error as lvl.

func (Line) Info

func (ln Line) Info(key string, value any) Line

Info calls Line.Add with Info as lvl.

func (Line) Warn

func (ln Line) Warn(key string, value any) Line

Warn calls Line.Add with Warn as lvl.

type Liner

type Liner interface {
	// Line should log attrs on specified severity level with a msg.
	// The implementer should assume attrs are read-only.
	Line(ctx context.Context, severity Level, msg string, attrs ...Attr)
}

Liner wraps basic Line method.

type LinerFunc

type LinerFunc func(ctx context.Context, sev Level, msg string, attrs ...Attr)

LinerFunc is an adapter to use functions where Liner is needed.

func Wrap

func Wrap(l *slog.Logger) LinerFunc

Wrap returns a LinerFunc that uses passed slog.Logger as the backing implementation. l is not checked for nil value.

func (LinerFunc) Line

func (lr LinerFunc) Line(ctx context.Context, sev Level, m string, a ...Attr)

Line calls lr with the passed parameters.

Jump to

Keyboard shortcuts

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