Common errors used with this package.
var ( ErrNoRequestContext = errors.New("no http request in context") ErrNoResponseWriterContext = errors.New("no http response in context") )
func Background() context.Context
Background returns a non-nil, empty Context. The background context provides a single key, "instance.id" that is globally unique to the process.
func GetRequest(ctx context.Context) (*http.Request, error)
GetRequest returns the http request in the given context. Returns ErrNoRequestContext if the context does not have an http request associated with it.
func GetRequestID(ctx context.Context) string
GetRequestID attempts to resolve the current request id, if possible. An error is return if it is not available on the context.
func GetResponseWriter(ctx context.Context) (http.ResponseWriter, error)
GetResponseWriter returns the http.ResponseWriter from the provided context. If not present, ErrNoResponseWriterContext is returned. The returned instance provides instrumentation in the context.
func GetStringValue(ctx context.Context, key interface{}) (value string)
GetStringValue returns a string value from the context. The empty string will be returned if not found.
func GetVersion(ctx context.Context) string
GetVersion returns the application version from the context. An empty string may returned if the version was not set on the context.
func RemoteAddr(r *http.Request) string
RemoteAddr extracts the remote address of the request, taking into account proxy headers.
func RemoteIP(r *http.Request) string
RemoteIP extracts the remote IP of the request, taking into account proxy headers.
func Since(ctx context.Context, key interface{}) time.Duration
Since looks up key, which should be a time.Time, and returns the duration since that time. If the key is not found, the value returned will be zero. This is helpful when inferring metrics related to context execution times.
func WithLogger(ctx context.Context, logger Logger) context.Context
WithLogger creates a new context with provided logger.
func WithRequest(ctx context.Context, r *http.Request) context.Context
WithRequest places the request on the context. The context of the request is assigned a unique id, available at "http.request.id". The request itself is available at "http.request". Other common attributes are available under the prefix "http.request.". If a request is already present on the context, this method will panic.
func WithResponseWriter(ctx context.Context, w http.ResponseWriter) (context.Context, http.ResponseWriter)
WithResponseWriter returns a new context and response writer that makes interesting response statistics available within the context.
func WithTrace(ctx context.Context) (context.Context, func(format string, a ...interface{}))
WithTrace allocates a traced timing span in a new context. This allows a caller to track the time between calling WithTrace and the returned done function. When the done function is called, a log message is emitted with a "trace.duration" field, corresponding to the elapsed time and a "trace.func" field, corresponding to the function that called WithTrace.
The logging keys "trace.id" and "trace.parent.id" are provided to implement dapper-like tracing. This function should be complemented with a WithSpan method that could be used for tracing distributed RPC calls.
The main benefit of this function is to post-process log messages or intercept them in a hook to provide timing data. Trace ids and parent ids can also be linked to provide call tracing, if so required.
Here is an example of the usage:
func timedOperation(ctx Context) { ctx, done := WithTrace(ctx) defer done("this will be the log message") // ... function body ... }
If the function ran for roughly 1s, such a usage would emit a log message as follows:
INFO[0001] this will be the log message trace.duration=1.004575763s trace.func=github.com/docker/distribution/context.traceOperation trace.id=<id> ...
Notice that the function name is automatically resolved, along with the package and a trace id is emitted that can be linked with parent ids.
func WithValues(ctx context.Context, m map[string]interface{}) context.Context
WithValues returns a context that proxies lookups through a map. Only supports string keys.
func WithVars(ctx context.Context, r *http.Request) context.Context
WithVars extracts gorilla/mux vars and makes them available on the returned context. Variables are available at keys with the prefix "vars.". For example, if looking for the variable "name", it can be accessed as "vars.name". Implementations that are accessing values need not know that the underlying context is implemented with gorilla/mux vars.
func WithVersion(ctx context.Context, version string) context.Context
WithVersion stores the application version in the context. The new context gets a logger to ensure log messages are marked with the application version.
Logger provides a leveled-logging interface.
type Logger interface { // standard logger methods Print(args ...interface{}) Printf(format string, args ...interface{}) Println(args ...interface{}) Fatal(args ...interface{}) Fatalf(format string, args ...interface{}) Fatalln(args ...interface{}) Panic(args ...interface{}) Panicf(format string, args ...interface{}) Panicln(args ...interface{}) // Leveled methods, from logrus Debug(args ...interface{}) Debugf(format string, args ...interface{}) Debugln(args ...interface{}) Error(args ...interface{}) Errorf(format string, args ...interface{}) Errorln(args ...interface{}) Info(args ...interface{}) Infof(format string, args ...interface{}) Infoln(args ...interface{}) Warn(args ...interface{}) Warnf(format string, args ...interface{}) Warnln(args ...interface{}) WithError(err error) *logrus.Entry }
func GetLogger(ctx context.Context, keys ...interface{}) Logger
GetLogger returns the logger from the current context, if present. If one or more keys are provided, they will be resolved on the context and included in the logger. While context.Value takes an interface, any key argument passed to GetLogger will be passed to fmt.Sprint when expanded as a logging key field. If context keys are integer constants, for example, its recommended that a String method is implemented.
func GetLoggerWithField(ctx context.Context, key, value interface{}, keys ...interface{}) Logger
GetLoggerWithField returns a logger instance with the specified field key and value without affecting the context. Extra specified keys will be resolved from the context.
func GetLoggerWithFields(ctx context.Context, fields map[interface{}]interface{}, keys ...interface{}) Logger
GetLoggerWithFields returns a logger instance with the specified fields without affecting the context. Extra specified keys will be resolved from the context.
func GetRequestLogger(ctx context.Context) Logger
GetRequestLogger returns a logger that contains fields from the request in the current context. If the request is not available in the context, no fields will display. Request loggers can safely be pushed onto the context.
func GetResponseLogger(ctx context.Context) Logger
GetResponseLogger reads the current response stats and builds a logger. Because the values are read at call time, pushing a logger returned from this function on the context will lead to missing or invalid data. Only call this at the end of a request, after the response has been written.