logging

package module
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2024 License: Apache-2.0 Imports: 15 Imported by: 1

README

logging

GoDoc License

Logging is a collection of collection of packages to make easy the logging experience.

Logging is currently in active development and it's API WILL CHANGE WITHOUT NOTICE.

logging/httplog - the HTTP middleware

Httplog implements and HTTP middleware that can optionally log the raw request and responses.

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/smallstep/logging"
    "github.com/smallstep/logging/httplog"
)

func main() {
    logger, err := logging.New("scim",
        logging.WithLogResponses(),
        logging.WithLogRequests(),
    )
    if err != nil {
        log.Fatal(err)
    }

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Hello World!")
    })

    srv := &http.Server{
        Addr:    ":8080",
        Handler: httplog.Middleware(logger, http.DefaultServeMux),
        ErrorLog: logger.StdLogger(logging.ErrorLevel),
    }

    logger.Infof("start listening at %s.", srv.Addr)
    log.Fatal(srv.ListenAndServe())
}

A simple curl http://localhost:8080 will print the following logs:

$ go run examples/httplog.go
{"level":"info","ts":1582944317.382856,"caller":"logging/logger.go:87","msg":"start listening at :8080."}
{"level":"info","ts":1582944330.861353,"caller":"httplog/handler.go:121","msg":"","name":"scim","request-id":"bpct0ijipt3avli7utp0","remote-address":"::1","time":"2020-02-28T18:45:30-08:00","duration":0.000064785,"duration-ns":64785,"method":"GET","path":"/","protocol":"HTTP/1.1","status":200,"size":13,"referer":"","user-agent":"curl/7.64.1","request":"R0VUIC8gSFRUUC8xLjENCkhvc3Q6IGxvY2FsaG9zdDo4MDgwDQpBY2NlcHQ6ICovKg0KVXNlci1BZ2VudDogY3VybC83LjY0LjENClgtVHJhY2UtSWQ6IGJwY3QwaWppcHQzYXZsaTd1dHAwDQoNCg==","response":"SGVsbG8gV29ybGQhCg=="}

Documentation

Index

Constants

View Source
const DefaultTraceHeader = "Traceparent"

DefaultTraceHeader is the default header used as a trace id.

Variables

This section is empty.

Functions

func GetName added in v0.3.0

func GetName(ctx context.Context) (string, bool)

GetName returns the log name from the context if it exists.

func GetTraceparent added in v0.0.4

func GetTraceparent(ctx context.Context) (*tracing.Traceparent, bool)

GetTraceparent returns the tracing id from the context if it exists.

func NewContext added in v0.4.0

func NewContext(ctx context.Context, logger *Logger) context.Context

NewContext adds the given logger to the context.

func NewTraceparent added in v0.0.4

func NewTraceparent() (*tracing.Traceparent, error)

NewTraceparent generates a new traceparent.

func Tracing added in v0.0.4

func Tracing(headerName string) func(next http.Handler) http.Handler

Tracing returns a new middleware that gets the given header and sets it in the context so it can be written in the logger. If the header does not exists or it's the empty string, it uses github.com/smallstep/tracing to create a new one.

func WithName added in v0.3.0

func WithName(ctx context.Context, name string) context.Context

WithName returns a new context with the given name in the context. This name will appear in the log entries that include the returning context.

func WithTraceparent added in v0.0.4

func WithTraceparent(ctx context.Context, tp *tracing.Traceparent) context.Context

WithTraceparent returns a new context with the given tracing id added to the context.

Types

type Level added in v0.2.0

type Level int8

Level indicates the log level.

const (
	DebugLevel Level = iota - 1
	InfoLevel
	WarnLevel
	ErrorLevel
	FatalLevel
)

func (Level) MarshalText added in v0.5.0

func (l Level) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler for Level.

func (Level) String added in v0.5.0

func (l Level) String() string

String implements fmt.Stringer for Level.

func (*Level) UnmarshalText added in v0.5.0

func (l *Level) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler for Level.

type Logger

type Logger struct {
	*zap.Logger
	// contains filtered or unexported fields
}

Logger is a request logger that uses zap.Logger as core.

func FromContext added in v0.4.0

func FromContext(ctx context.Context) (logger *Logger, ok bool)

FromContext returns a logger from the given context.

func New

func New(name string, opts ...Option) (*Logger, error)

New initializes the logger with the given options.

func (*Logger) Clone added in v0.0.7

func (l *Logger) Clone(opts ...zap.Option) *Logger

Clone creates a new copy of the logger with the given options.

func (*Logger) Debug added in v0.0.8

func (l *Logger) Debug(msg string, fields ...zap.Field)

Debug logs a message at debug level.

func (*Logger) Debugf

func (l *Logger) Debugf(format string, args ...interface{})

Debugf formats and logs a message at debug level.

func (*Logger) Error added in v0.0.8

func (l *Logger) Error(msg string, fields ...zap.Field)

Error logs a message at error level.

func (*Logger) Errorf

func (l *Logger) Errorf(format string, args ...interface{})

Errorf formats and logs a message at error level.

func (*Logger) Fatal added in v0.0.8

func (l *Logger) Fatal(msg string, fields ...zap.Field)

Fatal logs a message at fatal level and then calls to os.Exit(1).

func (*Logger) Fatalf added in v0.0.8

func (l *Logger) Fatalf(format string, args ...interface{})

Fatalf formats and logs a message at fatal level and then calls to os.Exit(1).

func (*Logger) Info added in v0.0.8

func (l *Logger) Info(msg string, fields ...zap.Field)

Info logs a message at info level.

func (*Logger) Infof

func (l *Logger) Infof(format string, args ...interface{})

Infof formats and logs a message at info level.

func (*Logger) LogRequests

func (l *Logger) LogRequests() bool

LogRequests returns if the logging of requests is enabled.

func (*Logger) LogResponses

func (l *Logger) LogResponses() bool

LogResponses returns if the logging of responses is enabled.

func (*Logger) Name

func (l *Logger) Name() string

Name returns the logging name.

func (*Logger) StdLogger added in v0.2.0

func (l *Logger) StdLogger(level Level) *log.Logger

StdLogger returns a *log.Logger with the specified log level.

func (*Logger) Sync

func (l *Logger) Sync() error

Sync calls the underlying Core's Sync method, flushing any buffered log entries. Applications should take care to call Sync before exiting.

func (*Logger) TimeFormat

func (l *Logger) TimeFormat() string

TimeFormat returns the configured time format.

func (*Logger) TraceHeader

func (l *Logger) TraceHeader() string

TraceHeader returns the trace header configured.

func (*Logger) Warn added in v0.0.9

func (l *Logger) Warn(msg string, fields ...zap.Field)

Warn logs a message at warn level.

func (*Logger) Warnf

func (l *Logger) Warnf(format string, args ...interface{})

Warnf formats and logs a message at warn level.

func (*Logger) Writer added in v0.2.0

func (l *Logger) Writer(level Level) io.Writer

Writer returns a io.Writer with the specified log level.

type Option

type Option func(o *options) error

Option is the type used to modify logger options.

func WithCallerSkip added in v0.0.8

func WithCallerSkip(skip int) Option

WithCallerSkip increases the number of callers skipped by caller annotation.

func WithConfig

func WithConfig(raw json.RawMessage) Option

WithConfig uses a JSON to configure the logger.

func WithFormatJSON

func WithFormatJSON() Option

WithFormatJSON configures the format of the logs as JSON. Defaults to text.

func WithFormatText

func WithFormatText() Option

WithFormatText configures the format of the logs as text. Defaults to text.

func WithLogLevel added in v0.5.0

func WithLogLevel(level Level) Option

WithLogLevel sets the verbosity of the logger.

func WithLogRequests

func WithLogRequests() Option

WithLogRequests enables the log of the requests.

func WithLogResponses

func WithLogResponses() Option

WithLogResponses enables the log of responses

func WithTimeFormat

func WithTimeFormat(format string) Option

WithTimeFormat sets a specific format for the time fields.

func WithTraceHeader

func WithTraceHeader(name string) Option

WithTraceHeader defines the name of the header used for tracing. Defaults to 'Traceparent'.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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