Documentation ¶
Index ¶
- Constants
- Variables
- func AsGoaMiddlewareLogger(ctx context.Context) middleware.Logger
- 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 ...interface{})
- func Endpoint(e goa.Endpoint) goa.Endpoint
- func Error(ctx context.Context, err error, keyvals ...Fielder)
- func Errorf(ctx context.Context, err error, format string, v ...interface{})
- func Fatal(ctx context.Context, err error, keyvals ...Fielder)
- func Fatalf(ctx context.Context, err error, format string, v ...interface{})
- 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 ...interface{})
- 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 ...interface{})
- 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 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 GRPCClientLogOption
- 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
- type LogrSink
- func (l *LogrSink) Enabled(level int) bool
- func (l *LogrSink) Error(err error, msg string, keysAndValues ...interface{})
- func (l *LogrSink) Info(level int, msg string, keysAndValues ...interface{})
- func (l *LogrSink) Init(info logr.RuntimeInfo)
- func (l *LogrSink) WithName(name string) logr.LogSink
- func (l *LogrSink) WithValues(keysAndValues ...any) logr.LogSink
- type Severity
- type StdLogger
- func (l *StdLogger) Fatal(v ...interface{})
- func (l *StdLogger) Fatalf(format string, v ...interface{})
- func (l *StdLogger) Fatalln(v ...interface{})
- func (l *StdLogger) Panic(v ...interface{})
- func (l *StdLogger) Panicf(format string, v ...interface{})
- func (l *StdLogger) Panicln(v ...interface{})
- func (l *StdLogger) Print(v ...interface{})
- func (l *StdLogger) Printf(format string, v ...interface{})
- func (l *StdLogger) Println(v ...interface{})
Examples ¶
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" GoaServiceKey = "goa.service" GoaMethodKey = "goa.method" )
var TimestampFormatLayout = time.RFC3339
TimestampFormatLayout is used to set the layout for our TimestampKey (default "time") values. Default format is time.RFC3339.
Functions ¶
func AsGoaMiddlewareLogger ¶ added in v0.3.0
func AsGoaMiddlewareLogger(ctx context.Context) middleware.Logger
AsGoaMiddlewareLogger creates a Goa middleware compatible logger that can be used when configuring Goa HTTP or gRPC servers.
Usage:
// HTTP server: import goahttp "goa.design/goa/v3/http" import httpmdlwr "goa.design/goa/v3/http/middleware" ... mux := goahttp.NewMuxer() handler := httpmdlwr.LogContext(log.AsGoaMiddlewareLogger)(mux) // gRPC server: import "google.golang.org/grpc" import grpcmiddleware "github.com/grpc-ecosystem/go-grpc-middleware" import grpcmdlwr "goa.design/goa/v3/grpc/middleware" ... srv := grpc.NewServer( grpcmiddleware.WithUnaryServerChain(grpcmdlwr.UnaryServerLogContext(log.AsGoaMiddlewareLogger)), )
func Client ¶ added in v0.11.0
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 ¶ added in v0.15.0
DebugEnabled returns true if the given context has debug logging enabled.
func Debugf ¶ added in v0.1.0
Debugf sets the key MessageKey (default "msg") and calls Debug. Arguments are handled in the manner of fmt.Printf.
func Endpoint ¶ added in v0.14.0
Endpoint is a Goa 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 ¶ added in v0.1.0
Errorf sets the key MessageKey (default "msg") and calls Error. Arguments are handled in the manner of fmt.Printf.
Example ¶
ctx := Context(context.Background()) err := errors.New("error") Info(ctx, KV{"hello", "world"}) // No output at this point because Info log events are buffered. // The call to Errorf causes the buffered events to be flushed. fmt.Println("---") Errorf(ctx, err, "failure")
Output: --- time=2022-02-22T17:00:00Z level=info hello=world time=2022-02-22T17:00:00Z level=error err=error msg=failure
func FlushAndDisableBuffering ¶ added in v0.1.0
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 ¶ added in v0.1.0
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 ¶ added in v0.5.0
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 Print ¶
Print writes the key/value pairs to the log output ignoring buffering.
Example ¶
ctx := Context(context.Background()) Print(ctx, KV{"hello", "world"})
Output: time=2022-02-22T17:00:00Z level=info hello=world
func Printf ¶ added in v0.1.0
Printf sets the key MessageKey (default "msg") and calls Print. Arguments are handled in the manner of fmt.Printf.
Example ¶
ctx := Context(context.Background()) Printf(ctx, "hello %s", "world")
Output: time=2022-02-22T17:00:00Z level=info msg="hello world"
func StreamClientInterceptor ¶ added in v0.11.0
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 ¶ added in v0.11.0
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.
Types ¶
type AWSLogger ¶ added in v0.10.0
AWSLogger returns an AWS SDK compatible logger.
func AsAWSLogger ¶ added in v0.10.0
AsAWSLogger returns an AWS SDK compatible logger.
Usage:
import "github.com/aws/aws-sdk-go-v2/config" import "goa.design/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 ¶ added in v0.6.0
type Fielder interface {
LogFields() []KV
}
Fielder is an interface that will return a slice of KV
type Fields ¶ added in v0.6.0
type Fields map[string]interface{}
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 ¶ added in v0.11.0
type GRPCClientLogOption = GRPCLogOption
GRPCClientLogOption is a function that applies a configuration option to a GRPC client interceptor logger. Deprecated: Use GRPCLogOption instead.
type GRPCLogOption ¶ added in v0.19.0
type GRPCLogOption func(*grpcOptions)
GRPCLogOption is a function that applies a configuration option to a GRPC interceptor logger.
func WithDisableCallID ¶ added in v1.0.0
func WithDisableCallID() GRPCLogOption
WithDisableCallID returns a GRPC logger option that disables the generation of request IDs.
func WithDisableCallLogging ¶ added in v0.19.0
func WithDisableCallLogging() GRPCLogOption
WithDisableCallLogging returns a GRPC logger option that disables call logging.
func WithErrorFunc ¶ added in v0.11.0
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 ¶ added in v0.11.0
type HTTPClientLogOption func(*httpClientOptions)
HTTPClientLogOption is a function that applies a configuration option to a HTTP client logger.
func WithErrorStatus ¶ added in v0.11.0
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 ¶ added in v0.13.0
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 ¶ added in v0.11.0
type HTTPLogOption func(*httpLogOptions)
HTTPLogOption is a function that applies a configuration option to log HTTP middleware.
func WithDisableRequestID ¶ added in v1.0.0
func WithDisableRequestID() HTTPLogOption
WithDisableRequestID returns a HTTP middleware option that disables the generation of request IDs.
func WithDisableRequestLogging ¶ added in v0.19.0
func WithDisableRequestLogging() HTTPLogOption
WithDisableRequestLogging returns a HTTP middleware option that disables logging of HTTP requests.
func WithPathFilter ¶ added in v0.6.0
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.
type KV ¶ added in v0.1.0
type KV struct { K string V interface{} }
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 ¶ added in v0.1.0
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 WithFunc ¶ added in v0.1.0
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 WithNoDebug ¶ added in v0.15.0
func WithNoDebug() LogOption
WithNoDebug disables debug logging.
type LogrSink ¶ added in v1.0.0
LogrSink returns a logr LogSink compatible logger.
func ToLogrSink ¶ added in v1.0.0
ToLogrSink returns a logr.LogSink.
Usage:
import "goa.design/clue/log" ctx := log.Context(context.Background()) sink := log.ToLogrSink(ctx) logger := logr.New(sink)
func (*LogrSink) Init ¶ added in v1.0.0
func (l *LogrSink) Init(info logr.RuntimeInfo)
type Severity ¶
type Severity int
Log severity enum
type StdLogger ¶ added in v0.3.0
type StdLogger struct {
// contains filtered or unexported fields
}
StdLogger implements an interface compatible with the stdlib log package.
func AsStdLogger ¶ added in v0.3.0
AsStdLogger adapts a Goa logger to a stdlib compatible logger.
func (*StdLogger) Fatal ¶ added in v0.3.0
func (l *StdLogger) Fatal(v ...interface{})
Fatal is equivalent to l.Print() followed by a call to os.Exit(1).
func (*StdLogger) Fatalf ¶ added in v0.3.0
Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1).
func (*StdLogger) Fatalln ¶ added in v0.3.0
func (l *StdLogger) Fatalln(v ...interface{})
Fatalln is equivalent to l.Println() followed by a call to os.Exit(1).
func (*StdLogger) Panic ¶ added in v0.3.0
func (l *StdLogger) Panic(v ...interface{})
Panic is equivalent to l.Print() followed by a call to panic().
func (*StdLogger) Panicf ¶ added in v0.3.0
Panicf is equivalent to l.Printf() followed by a call to panic().
func (*StdLogger) Panicln ¶ added in v0.3.0
func (l *StdLogger) Panicln(v ...interface{})
Panicln is equivalent to l.Println() followed by a call to panic().
func (*StdLogger) Print ¶ added in v0.3.0
func (l *StdLogger) Print(v ...interface{})
Print print to the logger. Arguments are handled in the manner of fmt.Print.