Documentation
¶
Index ¶
- Constants
- Variables
- func Client(t http.RoundTripper, opts ...HTTPClientLogOption) http.RoundTripper
- func Context(ctx context.Context, opts ...LogOption) context.Context
- func Debug(ctx context.Context, keyvals ...Fielder)
- func DebugEnabled(ctx context.Context) bool
- func Debugf(ctx context.Context, format string, v ...any)
- func Endpoint(e loom.Endpoint) loom.Endpoint
- func Error(ctx context.Context, err error, keyvals ...Fielder)
- func Errorf(ctx context.Context, err error, format string, v ...any)
- func Fatal(ctx context.Context, err error, keyvals ...Fielder)
- func Fatalf(ctx context.Context, err error, format string, v ...any)
- func FlushAndDisableBuffering(ctx context.Context)
- func FormatJSON(e *Entry) []byte
- func FormatTerminal(e *Entry) []byte
- func FormatText(e *Entry) []byte
- func HTTP(logCtx context.Context, opts ...HTTPLogOption) func(http.Handler) http.Handler
- func Info(ctx context.Context, keyvals ...Fielder)
- func Infof(ctx context.Context, format string, v ...any)
- func IsTerminal() bool
- func IsTracing(ctx context.Context) bool
- func MustContainLogger(logCtx context.Context)
- func Print(ctx context.Context, keyvals ...Fielder)
- func Printf(ctx context.Context, format string, v ...any)
- func StreamClientInterceptor(opts ...GRPCLogOption) grpc.StreamClientInterceptor
- func StreamServerInterceptor(logCtx context.Context, opts ...GRPCLogOption) grpc.StreamServerInterceptor
- func UnaryClientInterceptor(opts ...GRPCLogOption) grpc.UnaryClientInterceptor
- func UnaryServerInterceptor(logCtx context.Context, opts ...GRPCLogOption) grpc.UnaryServerInterceptor
- func Warn(ctx context.Context, keyvals ...Fielder)
- func Warnf(ctx context.Context, format string, v ...any)
- func With(ctx context.Context, keyvals ...Fielder) context.Context
- func WithContext(parentCtx, logCtx context.Context) context.Context
- type AWSLogger
- type DisableBufferingFunc
- type Entry
- type Fielder
- type Fields
- type FormatFunc
- type GRPCClientLogOptiondeprecated
- type GRPCLogOption
- type HTTPClientLogOption
- type HTTPLogOption
- type KV
- type LogOption
- func WithDebug() LogOption
- func WithDisableBuffering(fn DisableBufferingFunc) LogOption
- func WithFileLocation() LogOption
- func WithFormat(fn FormatFunc) LogOption
- func WithFunc(fn func(context.Context) []KV) LogOption
- func WithMaxSize(n int) LogOption
- func WithNoDebug() LogOption
- func WithOutput(w io.Writer) LogOption
- func WithOutputs(outputs ...Output) LogOption
- type LogrSink
- func (l *LogrSink) Enabled(level int) bool
- func (l *LogrSink) Error(err error, msg string, keysAndValues ...any)
- func (l *LogrSink) Info(level int, msg string, keysAndValues ...any)
- func (l *LogrSink) Init(info logr.RuntimeInfo)
- func (l *LogrSink) WithName(name string) logr.LogSink
- func (l *LogrSink) WithValues(keysAndValues ...any) logr.LogSink
- type MiddlewareLogger
- type Output
- type Severity
- type StdLogger
- func (l *StdLogger) Fatal(v ...any)
- func (l *StdLogger) Fatalf(format string, v ...any)
- func (l *StdLogger) Fatalln(v ...any)
- func (l *StdLogger) Panic(v ...any)
- func (l *StdLogger) Panicf(format string, v ...any)
- func (l *StdLogger) Panicln(v ...any)
- func (l *StdLogger) Print(v ...any)
- func (l *StdLogger) Printf(format string, v ...any)
- func (l *StdLogger) Println(v ...any)
Constants ¶
const DefaultMaxSize = 1024
DefaultMaxSize is the default maximum size of a single log message or value in bytes. It's also the maximum number of elements in a slice value.
const NameKey = "log"
NameKey is the key used to log the name of the logger.
Variables ¶
var ( TraceIDKey = "trace_id" SpanIDKey = "span_id" RequestIDKey = "request_id" MessageKey = "msg" ErrorMessageKey = "err" TimestampKey = "time" SeverityKey = "level" HTTPMethodKey = "http.method" HTTPURLKey = "http.url" HTTPFromKey = "http.remote_addr" HTTPStatusKey = "http.status" HTTPDurationKey = "http.time_ms" HTTPBytesKey = "http.bytes" HTTPBodyKey = "http.body" GRPCServiceKey = "grpc.service" GRPCMethodKey = "grpc.method" GRPCCodeKey = "grpc.code" GRPCStatusKey = "grpc.status" GRPCDurationKey = "grpc.time_ms" LoomServiceKey = "loom.service" LoomMethodKey = "loom.method" )
var ( ColorSeverityDebug = "\033[37m" ColorSeverityInfo = "\033[34m" ColorSeverityWarn = "\033[33m" ColorSeverityError = "\033[1;31m" )
Export color codes
var TimestampFormatLayout = time.RFC3339
TimestampFormatLayout is used to set the layout for our TimestampKey (default "time") values. Default format is time.RFC3339.
Functions ¶
func Client ¶
func Client(t http.RoundTripper, opts ...HTTPClientLogOption) http.RoundTripper
Client wraps the given roundtripper and log requests and responses using the clue logger stored in the request context.
func Debug ¶
Debug writes the key/value pairs to the log output if the log context is configured to log debug messages (via WithDebug).
func DebugEnabled ¶
DebugEnabled returns true if the given context has debug logging enabled.
func Debugf ¶
Debugf sets the key MessageKey (default "msg") and calls Debug. Arguments are handled in the manner of fmt.Printf.
func Endpoint ¶
Endpoint is a Loom endpoint middleware that adds the service and method names to the logged key/value pairs.
func Error ¶
Error flushes the log buffer and disables buffering if not already disabled. Error then sets the ErrorMessageKey (default "err") key with the given error and writes the key/value pairs to the log output.
func Errorf ¶
Errorf sets the key MessageKey (default "msg") and calls Error. Arguments are handled in the manner of fmt.Printf.
func FlushAndDisableBuffering ¶
FlushAndDisableBuffering flushes the log entries to the writer and stops buffering the given context.
func FormatJSON ¶
FormatJSON is a log formatter that prints entries using JSON. Entries are formatted as follows:
{
"time": "TIMESTAMP", // UTC timestamp in RFC3339 format
"level": "SEVERITY", // one of DEBUG, INFO or ERROR
"key1": "val1", // entry key/value pairs
"key2": "val2",
...
}
note: the implementation avoids using reflection (and thus the json package) for efficiency.
Output can be customised with log.TimestampKey, log.TimestampFormatLayout, and log.SeverityKey.
func FormatTerminal ¶
FormatTerminal is a log formatter that prints entries suitable for terminal that supports colors. It prints entries in the following format:
SEVERITY[seconds] key=val key=val ...
Where SEVERITY is one of DEBG, INFO or ERRO, seconds is the number of seconds since the application started, message is the log message, and key=val are the entry key/value pairs. The severity and keys are colored according to the severity (gray for debug entries, blue for info entries and red for errors).
func FormatText ¶
FormatText is the default log formatter when not running in a terminal, it prints entries using the logfmt format:
time=TIME level=SEVERITY KEY=VAL KEY=VAL ...
Where TIME is the UTC timestamp in RFC3339 format, SEVERITY is one of "debug", "info" or "error", and KEY=VAL are the entry key/value pairs. Values are quoted and escaped according to the logfmt specification.
Output can be customised with log.TimestampKey, log.TimestampFormatLayout, and log.SeverityKey.
func HTTP ¶
HTTP returns a HTTP middleware that performs two tasks:
- Enriches the request context with the logger specified in logCtx.
- Logs HTTP request details, except when WithDisableRequestLogging is set or URL path matches a WithPathFilter regex.
HTTP panics if logCtx was not created with Context.
func Infof ¶
Infof sets the key MessageKey (default "msg") and calls Info. Arguments are handled in the manner of fmt.Printf.
func IsTerminal ¶
func IsTerminal() bool
IsTerminal returns true if the process is running in a terminal.
func IsTracing ¶
IsTracing returns true if the context contains a trace created via the go.opentelemetry.io/otel/trace package. It is the default DisableBufferingFunc used by newly created loggers.
func MustContainLogger ¶
MustContainLogger will panic if the given context is missing the logger.
It can be used during server initialisation when you have a function or middleware that you want to ensure receives a context with a logger.
func Printf ¶
Printf sets the key MessageKey (default "msg") and calls Print. Arguments are handled in the manner of fmt.Printf.
func StreamClientInterceptor ¶
func StreamClientInterceptor(opts ...GRPCLogOption) grpc.StreamClientInterceptor
StreamClientInterceptor returns a stream interceptor that logs the request with the logger contained in the request context if any.
func StreamServerInterceptor ¶
func StreamServerInterceptor(logCtx context.Context, opts ...GRPCLogOption) grpc.StreamServerInterceptor
StreamServerInterceptor returns a stream interceptor that performs two tasks: 1. Enriches the request context with the logger specified in logCtx. 2. Logs details of the stream call, unless the WithDisableCallLogging option is provided. StreamServerInterceptor panics if logCtx was not created with Context.
func UnaryClientInterceptor ¶
func UnaryClientInterceptor(opts ...GRPCLogOption) grpc.UnaryClientInterceptor
UnaryClientInterceptor returns a unary interceptor that logs the request with the logger contained in the request context if any.
func UnaryServerInterceptor ¶
func UnaryServerInterceptor(logCtx context.Context, opts ...GRPCLogOption) grpc.UnaryServerInterceptor
UnaryServerInterceptor returns a unary interceptor that performs two tasks: 1. Enriches the request context with the logger specified in logCtx. 2. Logs details of the unary call, unless the WithDisableCallLogging option is provided. UnaryServerInterceptor panics if logCtx was not created with Context.
func Warn ¶
Warn writes the key/value pairs to the log buffer or output if buffering is disabled, with SeverityWarn.
func Warnf ¶
Warnf sets the key MessageKey (default "msg") and calls Warn. Arguments are handled in the manner of fmt.Printf.
Types ¶
type AWSLogger ¶
AWSLogger returns an AWS SDK compatible logger.
func AsAWSLogger ¶
AsAWSLogger returns an AWS SDK compatible logger.
Usage:
import "github.com/aws/aws-sdk-go-v2/config"
import "github.com/CaliLuke/loom/clue/log"
ctx := log.Context(context.Background())
httpc := &http.Client{Transport: otelhttp.NewTransport(http.DefaultTransport)}
cfg, err := config.LoadDefaultConfig(ctx,
config.WithHTTPClient(httpc),
config.WithLogger(log.AsAWSLogger(ctx)))
type DisableBufferingFunc ¶
DisableBufferingFunc is a function that returns true if the logger should disable buffering for the given context.
type Fielder ¶
type Fielder interface {
LogFields() []KV
}
Fielder is an interface that will return a slice of KV
type Fields ¶
Fields allows to quickly define fields for cases where you are OK with non-deterministic order of the fields
type FormatFunc ¶
FormatFunc is a function that formats a log entry.
type GRPCClientLogOption
deprecated
type GRPCClientLogOption = GRPCLogOption
GRPCClientLogOption is a function that applies a configuration option to a GRPC client interceptor logger.
Deprecated: Use GRPCLogOption instead.
type GRPCLogOption ¶
type GRPCLogOption func(*grpcOptions)
GRPCLogOption is a function that applies a configuration option to a GRPC interceptor logger.
func WithCallLogFunc ¶
func WithCallLogFunc(logFunc func(ctx context.Context, keyvals ...Fielder)) GRPCLogOption
WithCallLogFunc returns a GRPC logger option that configures the logger to use the given log function instead of log.Print() as default.
func WithDisableCallID ¶
func WithDisableCallID() GRPCLogOption
WithDisableCallID returns a GRPC logger option that disables the generation of request IDs.
func WithDisableCallLogging ¶
func WithDisableCallLogging() GRPCLogOption
WithDisableCallLogging returns a GRPC logger option that disables call logging.
func WithErrorFunc ¶
func WithErrorFunc(iserr func(codes.Code) bool) GRPCLogOption
WithErrorFunc returns a GRPC logger option that configures the logger to consider the given function to determine if a GRPC status code is an error.
type HTTPClientLogOption ¶
type HTTPClientLogOption func(*httpClientOptions)
HTTPClientLogOption is a function that applies a configuration option to a HTTP client logger.
func WithErrorStatus ¶
func WithErrorStatus(status int) HTTPClientLogOption
WithErrorStatus returns a HTTP client logger option that configures the logger to log errors for responses with the given status code.
func WithLogBodyOnError ¶
func WithLogBodyOnError() HTTPClientLogOption
WithLogBodyOnError returns a HTTP client logger option that configures the logger to log the response body when the response status code is an error.
type HTTPLogOption ¶
type HTTPLogOption func(*httpLogOptions)
HTTPLogOption is a function that applies a configuration option to log HTTP middleware.
func WithDisableRequestID ¶
func WithDisableRequestID() HTTPLogOption
WithDisableRequestID returns a HTTP middleware option that disables the generation of request IDs.
func WithDisableRequestLogging ¶
func WithDisableRequestLogging() HTTPLogOption
WithDisableRequestLogging returns a HTTP middleware option that disables logging of HTTP requests.
func WithPathFilter ¶
func WithPathFilter(filter *regexp.Regexp) HTTPLogOption
WithPathFilter adds a path filter to the HTTP middleware. Requests whose path match the filter are not logged. WithPathFilter can be called multiple times to add multiple filters.
func WithRequestLogFunc ¶
func WithRequestLogFunc(logFunc func(ctx context.Context, keyvals ...Fielder)) HTTPLogOption
WithRequestLogFunc returns a HTTP middleware option that configures the logger to use the given log function instead of log.Print() as default.
type KV ¶
KV represents a key/value pair. Values must be strings, numbers, booleans, nil or a slice of these types.
type LogOption ¶
type LogOption func(*options)
LogOption is a function that applies a configuration option to a logger.
func WithDisableBuffering ¶
func WithDisableBuffering(fn DisableBufferingFunc) LogOption
WithDisableBuffering sets the DisableBufferingFunc called to assess whether buffering should be disabled.
func WithFileLocation ¶
func WithFileLocation() LogOption
WithFileLocation adds the "file" key to each log entry with the parent directory, file and line number of the caller: "file=dir/file.go:123".
func WithFormat ¶
func WithFormat(fn FormatFunc) LogOption
WithFormat sets the log format.
This option exists for backward compatibility. When used in conjunction with WithOutputs, it updates the first output format.
func WithFunc ¶
WithFunc sets a key/value pair generator function to be called with every log entry. The generated key/value pairs are added to the log entry.
func WithMaxSize ¶
WithMaxSize sets the maximum size of a single log message or value.
func WithOutput ¶
WithOutput sets the log output.
This option exists for backward compatibility. When used in conjunction with WithOutputs, it updates the first output writer.
func WithOutputs ¶
WithOutputs sets the log outputs.
Each output formats the entry then writes it to its writer. This makes it possible to log to multiple destinations with independent formats (e.g. terminal colors on stdout and JSON to a file).
type LogrSink ¶
LogrSink returns a logr LogSink compatible logger.
func ToLogrSink ¶
ToLogrSink returns a logr.LogSink.
Usage:
import "github.com/CaliLuke/loom/clue/log" ctx := log.Context(context.Background()) sink := log.ToLogrSink(ctx) logger := logr.New(sink)
func (*LogrSink) Init ¶
func (l *LogrSink) Init(info logr.RuntimeInfo)
type MiddlewareLogger ¶
MiddlewareLogger is the minimal structured logger interface used by Loom middleware adapters.
func AsLoomMiddlewareLogger ¶
func AsLoomMiddlewareLogger(ctx context.Context) MiddlewareLogger
AsLoomMiddlewareLogger creates a middleware-compatible logger that can be used when configuring generated HTTP or gRPC servers.
Usage:
// HTTP server:
import loomhttp "github.com/CaliLuke/loom/http"
import httpmdlwr "github.com/CaliLuke/loom/http/middleware"
...
mux := loomhttp.NewMuxer()
handler := httpmdlwr.LogContext(log.AsLoomMiddlewareLogger)(mux)
// gRPC server:
import "google.golang.org/grpc"
import grpcmiddleware "github.com/grpc-ecosystem/go-grpc-middleware"
import grpcmdlwr "github.com/CaliLuke/loom/grpc/middleware"
...
srv := grpc.NewServer(
grpcmiddleware.WithUnaryServerChain(grpcmdlwr.UnaryServerLogContext(log.AsLoomMiddlewareLogger)),
)
type Output ¶
type Output struct {
// Writer receives the formatted log bytes.
Writer io.Writer
// Format turns a log entry into bytes suitable for Writer.
Format FormatFunc
}
Output configures where log entries are written and how they are formatted.
Output is the unit of configuration for "fanout" logging: a single log entry can be written to multiple outputs, each with its own formatting.
Writer and Format must be non-nil.
type Severity ¶
type Severity int
Log severity enum
type StdLogger ¶
type StdLogger struct {
// contains filtered or unexported fields
}
StdLogger implements an interface compatible with the stdlib log package.
func AsStdLogger ¶
AsStdLogger adapts a Loom logger to a stdlib compatible logger.
func (*StdLogger) Print ¶
Print print to the logger. Arguments are handled in the manner of fmt.Print.