4b14eef595
The new context package supports context-aware logging, integrating with logrus. Several utilities are provided to associate http requests with a context, ensuring that one can trace log messages all the way through a context-aware call stack. A full description of this functionality is available in doc.go. Signed-off-by: Stephen J Day <stephen.day@docker.com>
35 lines
834 B
Go
35 lines
834 B
Go
package context
|
|
|
|
import (
|
|
"time"
|
|
|
|
"golang.org/x/net/context"
|
|
)
|
|
|
|
// 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 Since(ctx context.Context, key interface{}) time.Duration {
|
|
startedAtI := ctx.Value(key)
|
|
if startedAtI != nil {
|
|
if startedAt, ok := startedAtI.(time.Time); ok {
|
|
return time.Since(startedAt)
|
|
}
|
|
}
|
|
|
|
return 0
|
|
}
|
|
|
|
// GetStringValue returns a string value from the context. The empty string
|
|
// will be returned if not found.
|
|
func GetStringValue(ctx context.Context, key string) (value string) {
|
|
stringi := ctx.Value(key)
|
|
if stringi != nil {
|
|
if valuev, ok := stringi.(string); ok {
|
|
value = valuev
|
|
}
|
|
}
|
|
|
|
return value
|
|
}
|