log

package
v1.9.1 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2024 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Overview

Package log wraps the go.uber.org/zap log package. It provides methods that attach loggers to middleware, grpc servers, and http.RoundTrippers

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Get

func Get(ctx context.Context) *zap.Logger

Get returns the logger wrapped with the given context. This function is intended to be used as a mechanism for adding scoped arbitrary logging information to the logger. If a nil context is passed, the default global logger is returned.

Example

Create logger

testLogger := Get(context.Background())
fmt.Printf("%T", testLogger)
Output:

*zap.Logger

func HTTPServerMiddleware added in v0.22.0

func HTTPServerMiddleware(next http.Handler) http.Handler

HTTPServerMiddleware logs a series of standard attributes for every HTTP request and attaches a logger onto the request context.

On inbound request received these attributes include:

* The remote address of the client * The HTTP Method utilized

On outbound response return these attributes include all of the above as well as: * HTTP response code Note that this middleware must be attached after writer.StatusRecorderMiddleware for HTTP response code logging to function and after tracing.HTTPServerMiddleware for trace ids to show up in logs.

Example

Get logging middleware function for HTTP Server

f := HTTPServerMiddleware
fmt.Printf("%T", f)
Output:

func(http.Handler) http.Handler

func NewContext

func NewContext(ctx context.Context, l *zap.Logger) context.Context

NewContext creates and returns a new context with a wrapped logger. If a logger is not provided, the context returned will contain the global logger. This concept is useful if you wish for all downstream logs from the site of a given context to include some contextual fields or use a sub-logger. For example, once your application has unpacked the Trace ID, you may wish to log that information with every future request.

func RegisterLogLevelHandler added in v0.45.0

func RegisterLogLevelHandler(router *mux.Router)

RegisterLogLevelHandler registers an endpoint handler with the specified router to change the global log level for the application. Once the handler is registered, the log level can be changed with an HTTP PUT request to the endpoint with the desired log level. e.g. curl -X PUT -d '{"level":"debug"}' 127.0.0.1:8080/loglevel

func SQLMiddleware added in v0.3.0

func SQLMiddleware(ctx context.Context, queryName, query string, _ ...interface{}) (context.Context, sqlMiddleware.End, error)

SQLMiddleware debug logs requests made against SQL databases.

func StreamServerInterceptor added in v0.16.1

func StreamServerInterceptor(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error

StreamServerInterceptor returns a new streaming server interceptor that includes a logger in context This code is heavily inspired by the excellent open-source grpc middleware library: https://github.com/grpc-ecosystem/go-grpc-middleware/blob/master/logging/zap/server_interceptors.go We have chosen to reimplement some aspects of this functionality to more specifically fit our logging needs.

func UnaryServerInterceptor added in v0.16.1

func UnaryServerInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error)

UnaryServerInterceptor returns a new unary server interceptor that includes a logger in context This code is heavily inspired by the excellent open-source grpc middleware library: https://github.com/grpc-ecosystem/go-grpc-middleware/blob/master/logging/zap/server_interceptors.go We have chosen to reimplement some aspects of this functionality to more specifically fit our logging needs.

Types

type Config

type Config struct {
	Fields map[string]interface{} // These fields will be applied to all logs. Strongly recommend `version` at a minimum.

	Level                string         // The level at which logs should be produced. Defaults to INFO
	Encoding             string         // One of "json" or "console"
	OutputPaths          []string       // List of locations where logs should be placed. Defaults to stdout
	ErrorOutputPaths     []string       // List of locations where error logs should be placed. Defaults to stderr
	Cores                []zapcore.Core // Provides optional functionality to allow users to Tee log output to additional Log cores
	Options              []zap.Option   // Users may specify any additional zap logger options which override defaults
	SamplingInitial      int            // Initial sampling rate for the logger for each cycle
	SamplingThereafter   int            // Sampling rate after that initial cap is hit, per cycle
	UseDevelopmentLogger bool           // If true, use default zap development logger settings
	// contains filtered or unexported fields
}

Config defines the necessary configuration for instantiating a Logger

Example

Initialize log package

c := Config{UseDevelopmentLogger: true}
err := c.InitializeLogger()
fmt.Printf("%v", err)
Output:

<nil>

func (Config) InitializeLogger

func (c Config) InitializeLogger() error

InitializeLogger sets up the logger. This function should be called as soon as possible. Any use of the logger provided by this package will be a nop until this function is called.

func (*Config) RegisterFlags

func (c *Config) RegisterFlags(flags *pflag.FlagSet)

RegisterFlags register Logging flags with pflags

type RoundTripper added in v0.24.0

type RoundTripper struct {
	RoundTripper http.RoundTripper
}

RoundTripper provides a proxied HTTP RoundTripper which logs client HTTP request details

Example

Get logging http.RoundTripper

rt := (http.RoundTripper)(RoundTripper{})
fmt.Printf("%T", rt)
Output:

log.RoundTripper

func (RoundTripper) RoundTrip added in v0.24.0

func (rt RoundTripper) RoundTrip(r *http.Request) (*http.Response, error)

RoundTrip completes HTTP roundtrips while logging HTTP request details

Jump to

Keyboard shortcuts

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