X Tutup
Skip to content

Commit b8e1fa2

Browse files
committed
log: provide simple context logging
We consolidate simple context logging for use across packages. For now, one still needs logrus, but we can take this further and avoid the import at a later time. Signed-off-by: Stephen J Day <stephen.day@docker.com>
0 parents  commit b8e1fa2

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

log/context.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package log
2+
3+
import (
4+
"github.com/Sirupsen/logrus"
5+
"golang.org/x/net/context"
6+
)
7+
8+
var (
9+
// G is an alias for GetLogger.
10+
//
11+
// We may want to define this locally to a package to get package tagged log
12+
// messages.
13+
G = GetLogger
14+
15+
// L is an alias for the the standard logger.
16+
L = logrus.NewEntry(logrus.StandardLogger())
17+
)
18+
19+
type loggerKey struct{}
20+
21+
// WithLogger returns a new context with the provided logger. Use in
22+
// combination with logger.WithField(s) for great effect.
23+
func WithLogger(ctx context.Context, logger *logrus.Entry) context.Context {
24+
return context.WithValue(ctx, loggerKey{}, logger)
25+
}
26+
27+
// GetLogger retrieves the current logger from the context. If no logger is
28+
// available, the default logger is returned.
29+
func GetLogger(ctx context.Context) *logrus.Entry {
30+
logger := ctx.Value(loggerKey{})
31+
32+
if logger == nil {
33+
return L
34+
}
35+
36+
return logger.(*logrus.Entry)
37+
}

0 commit comments

Comments
 (0)
X Tutup