Created
November 18, 2016 21:29
-
-
Save sheenobu/4548fa53f2ff94523c53265feb368088 to your computer and use it in GitHub Desktop.
contextual logging
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Package log implements logging attached to golang.org/x/net/context | |
package log | |
import ( | |
"golang.org/x/net/context" | |
log15 "gopkg.in/inconshreveable/log15.v2" | |
) | |
type logKeyType int | |
var logKey logKeyType | |
// SetLog sets the log on the context | |
func SetLog(ctx context.Context, l log15.Logger) context.Context { | |
return context.WithValue(ctx, logKey, l) | |
} | |
// NewContext creates a context with the log populated | |
func NewContext(ctx context.Context, args ...interface{}) context.Context { | |
l := log15.New(args...) | |
return context.WithValue(ctx, logKey, l) | |
} | |
// FromContext gets the logger out of the context | |
func FromContext(ctx context.Context) (log15.Logger, bool) { | |
l, ok := ctx.Value(logKey).(log15.Logger) | |
return l, ok | |
} | |
// Log gets the log from the context | |
func Log(ctx context.Context) log15.Logger { | |
l, ok := FromContext(ctx) | |
if !ok { | |
l = log15.New() | |
} | |
return l | |
} | |
// Error writes a error log entry | |
func Error(ctx context.Context, msg string, v ...interface{}) { | |
Log(ctx).Error(msg, v...) | |
} | |
// Crit writes a critical log entry | |
func Crit(ctx context.Context, msg string, v ...interface{}) { | |
Log(ctx).Crit(msg, v...) | |
} | |
// Warn writes a warning log entry | |
func Warn(ctx context.Context, msg string, v ...interface{}) { | |
Log(ctx).Warn(msg, v...) | |
} | |
// Info writes a info log entry | |
func Info(ctx context.Context, msg string, v ...interface{}) { | |
Log(ctx).Info(msg, v...) | |
} | |
// Debug writes a debug log entry | |
func Debug(ctx context.Context, msg string, v ...interface{}) { | |
Log(ctx).Debug(msg, v...) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage: