1
0
Fork 0
mirror of https://github.com/moby/moby.git synced 2022-11-09 12:21:53 -05:00

Merge pull request #28852 from miaoyq/rename-log-context

Rename 'context' to 'loginfo' in the logger module
This commit is contained in:
Sebastiaan van Stijn 2016-12-30 01:13:50 +01:00 committed by GitHub
commit a331056268
18 changed files with 191 additions and 191 deletions

View file

@ -328,7 +328,7 @@ func (container *Container) StartLogger() (logger.Logger, error) {
if err != nil {
return nil, fmt.Errorf("failed to get logging factory: %v", err)
}
ctx := logger.Context{
info := logger.Info{
Config: cfg.Config,
ContainerID: container.ID,
ContainerName: container.Name,
@ -344,12 +344,12 @@ func (container *Container) StartLogger() (logger.Logger, error) {
// Set logging file for "json-logger"
if cfg.Type == jsonfilelog.Name {
ctx.LogPath, err = container.GetRootResourcePath(fmt.Sprintf("%s-json.log", container.ID))
info.LogPath, err = container.GetRootResourcePath(fmt.Sprintf("%s-json.log", container.ID))
if err != nil {
return nil, err
}
}
return c(ctx)
return c(info)
}
// GetProcessLabel returns the process label for the container.

View file

@ -88,17 +88,17 @@ func init() {
// also taken from environment variables AWS_REGION, AWS_ACCESS_KEY_ID,
// AWS_SECRET_ACCESS_KEY, the shared credentials file (~/.aws/credentials), and
// the EC2 Instance Metadata Service.
func New(ctx logger.Context) (logger.Logger, error) {
logGroupName := ctx.Config[logGroupKey]
logStreamName, err := loggerutils.ParseLogTag(ctx, "{{.FullID}}")
func New(info logger.Info) (logger.Logger, error) {
logGroupName := info.Config[logGroupKey]
logStreamName, err := loggerutils.ParseLogTag(info, "{{.FullID}}")
if err != nil {
return nil, err
}
if ctx.Config[logStreamKey] != "" {
logStreamName = ctx.Config[logStreamKey]
if info.Config[logStreamKey] != "" {
logStreamName = info.Config[logStreamKey]
}
client, err := newAWSLogsClient(ctx)
client, err := newAWSLogsClient(info)
if err != nil {
return nil, err
}
@ -127,13 +127,13 @@ var newRegionFinder = func() regionFinder {
// Customizations to the default client from the SDK include a Docker-specific
// User-Agent string and automatic region detection using the EC2 Instance
// Metadata Service when region is otherwise unspecified.
func newAWSLogsClient(ctx logger.Context) (api, error) {
func newAWSLogsClient(info logger.Info) (api, error) {
var region *string
if os.Getenv(regionEnvKey) != "" {
region = aws.String(os.Getenv(regionEnvKey))
}
if ctx.Config[regionKey] != "" {
region = aws.String(ctx.Config[regionKey])
if info.Config[regionKey] != "" {
region = aws.String(info.Config[regionKey])
}
if region == nil || *region == "" {
logrus.Info("Trying to get region from EC2 Metadata")

View file

@ -28,13 +28,13 @@ const (
)
func TestNewAWSLogsClientUserAgentHandler(t *testing.T) {
ctx := logger.Context{
info := logger.Info{
Config: map[string]string{
regionKey: "us-east-1",
},
}
client, err := newAWSLogsClient(ctx)
client, err := newAWSLogsClient(info)
if err != nil {
t.Fatal(err)
}
@ -59,7 +59,7 @@ func TestNewAWSLogsClientUserAgentHandler(t *testing.T) {
}
func TestNewAWSLogsClientRegionDetect(t *testing.T) {
ctx := logger.Context{
info := logger.Info{
Config: map[string]string{},
}
@ -71,7 +71,7 @@ func TestNewAWSLogsClientRegionDetect(t *testing.T) {
successResult: "us-east-1",
}
_, err := newAWSLogsClient(ctx)
_, err := newAWSLogsClient(info)
if err != nil {
t.Fatal(err)
}
@ -695,12 +695,12 @@ func TestCollectBatchWithDuplicateTimestamps(t *testing.T) {
func TestCreateTagSuccess(t *testing.T) {
mockClient := newMockClient()
ctx := logger.Context{
info := logger.Info{
ContainerName: "/test-container",
ContainerID: "container-abcdefghijklmnopqrstuvwxyz01234567890",
Config: map[string]string{"tag": "{{.Name}}/{{.FullID}}"},
}
logStreamName, e := loggerutils.ParseLogTag(ctx, loggerutils.DefaultTemplate)
logStreamName, e := loggerutils.ParseLogTag(info, loggerutils.DefaultTemplate)
if e != nil {
t.Errorf("Error generating tag: %q", e)
}

View file

@ -54,17 +54,17 @@ func init() {
}
// New creates a new etwLogs logger for the given container and registers the EWT provider.
func New(ctx logger.Context) (logger.Logger, error) {
func New(info logger.Info) (logger.Logger, error) {
if err := registerETWProvider(); err != nil {
return nil, err
}
logrus.Debugf("logging driver etwLogs configured for container: %s.", ctx.ContainerID)
logrus.Debugf("logging driver etwLogs configured for container: %s.", info.ContainerID)
return &etwLogs{
containerName: ctx.Name(),
imageName: ctx.ContainerImageName,
containerID: ctx.ContainerID,
imageID: ctx.ContainerImageID,
containerName: info.Name(),
imageName: info.ContainerImageName,
containerID: info.ContainerID,
imageID: info.ContainerImageID,
}, nil
}

View file

@ -6,7 +6,7 @@ import (
)
// Creator builds a logging driver instance with given context.
type Creator func(Context) (Logger, error)
type Creator func(Info) (Logger, error)
// LogOptValidator checks the options specific to the underlying
// logging implementation.

View file

@ -67,22 +67,22 @@ func init() {
// New creates a fluentd logger using the configuration passed in on
// the context. The supported context configuration variable is
// fluentd-address.
func New(ctx logger.Context) (logger.Logger, error) {
loc, err := parseAddress(ctx.Config[addressKey])
func New(info logger.Info) (logger.Logger, error) {
loc, err := parseAddress(info.Config[addressKey])
if err != nil {
return nil, err
}
tag, err := loggerutils.ParseLogTag(ctx, loggerutils.DefaultTemplate)
tag, err := loggerutils.ParseLogTag(info, loggerutils.DefaultTemplate)
if err != nil {
return nil, err
}
extra := ctx.ExtraAttributes(nil)
extra := info.ExtraAttributes(nil)
bufferLimit := defaultBufferLimit
if ctx.Config[bufferLimitKey] != "" {
bl64, err := units.RAMInBytes(ctx.Config[bufferLimitKey])
if info.Config[bufferLimitKey] != "" {
bl64, err := units.RAMInBytes(info.Config[bufferLimitKey])
if err != nil {
return nil, err
}
@ -90,8 +90,8 @@ func New(ctx logger.Context) (logger.Logger, error) {
}
retryWait := defaultRetryWait
if ctx.Config[retryWaitKey] != "" {
rwd, err := time.ParseDuration(ctx.Config[retryWaitKey])
if info.Config[retryWaitKey] != "" {
rwd, err := time.ParseDuration(info.Config[retryWaitKey])
if err != nil {
return nil, err
}
@ -99,8 +99,8 @@ func New(ctx logger.Context) (logger.Logger, error) {
}
maxRetries := defaultMaxRetries
if ctx.Config[maxRetriesKey] != "" {
mr64, err := strconv.ParseUint(ctx.Config[maxRetriesKey], 10, strconv.IntSize)
if info.Config[maxRetriesKey] != "" {
mr64, err := strconv.ParseUint(info.Config[maxRetriesKey], 10, strconv.IntSize)
if err != nil {
return nil, err
}
@ -108,8 +108,8 @@ func New(ctx logger.Context) (logger.Logger, error) {
}
asyncConnect := false
if ctx.Config[asyncConnectKey] != "" {
if asyncConnect, err = strconv.ParseBool(ctx.Config[asyncConnectKey]); err != nil {
if info.Config[asyncConnectKey] != "" {
if asyncConnect, err = strconv.ParseBool(info.Config[asyncConnectKey]); err != nil {
return nil, err
}
}
@ -125,7 +125,7 @@ func New(ctx logger.Context) (logger.Logger, error) {
AsyncConnect: asyncConnect,
}
logrus.WithField("container", ctx.ContainerID).WithField("config", fluentConfig).
logrus.WithField("container", info.ContainerID).WithField("config", fluentConfig).
Debug("logging driver fluentd configured")
log, err := fluent.New(fluentConfig)
@ -134,8 +134,8 @@ func New(ctx logger.Context) (logger.Logger, error) {
}
return &fluentd{
tag: tag,
containerID: ctx.ContainerID,
containerName: ctx.ContainerName,
containerID: info.ContainerID,
containerName: info.ContainerName,
writer: log,
extra: extra,
}, nil

View file

@ -100,14 +100,14 @@ func initGCP() {
// default credentials.
//
// See https://developers.google.com/identity/protocols/application-default-credentials
func New(ctx logger.Context) (logger.Logger, error) {
func New(info logger.Info) (logger.Logger, error) {
initGCP()
var project string
if projectID != "" {
project = projectID
}
if projectID, found := ctx.Config[projectOptKey]; found {
if projectID, found := info.Config[projectOptKey]; found {
project = projectID
}
if project == "" {
@ -136,17 +136,17 @@ func New(ctx logger.Context) (logger.Logger, error) {
l := &gcplogs{
logger: lg,
container: &containerInfo{
Name: ctx.ContainerName,
ID: ctx.ContainerID,
ImageName: ctx.ContainerImageName,
ImageID: ctx.ContainerImageID,
Created: ctx.ContainerCreated,
Metadata: ctx.ExtraAttributes(nil),
Name: info.ContainerName,
ID: info.ContainerID,
ImageName: info.ContainerImageName,
ImageID: info.ContainerImageID,
Created: info.ContainerCreated,
Metadata: info.ExtraAttributes(nil),
},
}
if ctx.Config[logCmdKey] == "true" {
l.container.Command = ctx.Command()
if info.Config[logCmdKey] == "true" {
l.container.Command = info.Command()
}
if onGCE {
@ -155,11 +155,11 @@ func New(ctx logger.Context) (logger.Logger, error) {
Name: instanceName,
ID: instanceID,
}
} else if ctx.Config[logZoneKey] != "" || ctx.Config[logNameKey] != "" || ctx.Config[logIDKey] != "" {
} else if info.Config[logZoneKey] != "" || info.Config[logNameKey] != "" || info.Config[logIDKey] != "" {
l.instance = &instanceInfo{
Zone: ctx.Config[logZoneKey],
Name: ctx.Config[logNameKey],
ID: ctx.Config[logIDKey],
Zone: info.Config[logZoneKey],
Name: info.Config[logNameKey],
ID: info.Config[logIDKey],
}
}

View file

@ -24,7 +24,7 @@ const name = "gelf"
type gelfLogger struct {
writer *gelf.Writer
ctx logger.Context
info logger.Info
hostname string
rawExtra json.RawMessage
}
@ -40,36 +40,36 @@ func init() {
// New creates a gelf logger using the configuration passed in on the
// context. The supported context configuration variable is gelf-address.
func New(ctx logger.Context) (logger.Logger, error) {
func New(info logger.Info) (logger.Logger, error) {
// parse gelf address
address, err := parseAddress(ctx.Config["gelf-address"])
address, err := parseAddress(info.Config["gelf-address"])
if err != nil {
return nil, err
}
// collect extra data for GELF message
hostname, err := ctx.Hostname()
hostname, err := info.Hostname()
if err != nil {
return nil, fmt.Errorf("gelf: cannot access hostname to set source field")
}
// parse log tag
tag, err := loggerutils.ParseLogTag(ctx, loggerutils.DefaultTemplate)
tag, err := loggerutils.ParseLogTag(info, loggerutils.DefaultTemplate)
if err != nil {
return nil, err
}
extra := map[string]interface{}{
"_container_id": ctx.ContainerID,
"_container_name": ctx.Name(),
"_image_id": ctx.ContainerImageID,
"_image_name": ctx.ContainerImageName,
"_command": ctx.Command(),
"_container_id": info.ContainerID,
"_container_name": info.Name(),
"_image_id": info.ContainerImageID,
"_image_name": info.ContainerImageName,
"_command": info.Command(),
"_tag": tag,
"_created": ctx.ContainerCreated,
"_created": info.ContainerCreated,
}
extraAttrs := ctx.ExtraAttributes(func(key string) string {
extraAttrs := info.ExtraAttributes(func(key string) string {
if key[0] == '_' {
return key
}
@ -90,7 +90,7 @@ func New(ctx logger.Context) (logger.Logger, error) {
return nil, fmt.Errorf("gelf: cannot connect to GELF endpoint: %s %v", address, err)
}
if v, ok := ctx.Config["gelf-compression-type"]; ok {
if v, ok := info.Config["gelf-compression-type"]; ok {
switch v {
case "gzip":
gelfWriter.CompressionType = gelf.CompressGzip
@ -103,7 +103,7 @@ func New(ctx logger.Context) (logger.Logger, error) {
}
}
if v, ok := ctx.Config["gelf-compression-level"]; ok {
if v, ok := info.Config["gelf-compression-level"]; ok {
val, err := strconv.Atoi(v)
if err != nil {
return nil, fmt.Errorf("gelf: invalid compression level %s, err %v", v, err)
@ -113,7 +113,7 @@ func New(ctx logger.Context) (logger.Logger, error) {
return &gelfLogger{
writer: gelfWriter,
ctx: ctx,
info: info,
hostname: hostname,
rawExtra: rawExtra,
}, nil

View file

@ -58,24 +58,24 @@ func sanitizeKeyMod(s string) string {
// New creates a journald logger using the configuration passed in on
// the context.
func New(ctx logger.Context) (logger.Logger, error) {
func New(info logger.Info) (logger.Logger, error) {
if !journal.Enabled() {
return nil, fmt.Errorf("journald is not enabled on this host")
}
// parse log tag
tag, err := loggerutils.ParseLogTag(ctx, loggerutils.DefaultTemplate)
tag, err := loggerutils.ParseLogTag(info, loggerutils.DefaultTemplate)
if err != nil {
return nil, err
}
vars := map[string]string{
"CONTAINER_ID": ctx.ContainerID[:12],
"CONTAINER_ID_FULL": ctx.ContainerID,
"CONTAINER_NAME": ctx.Name(),
"CONTAINER_ID": info.ContainerID[:12],
"CONTAINER_ID_FULL": info.ContainerID,
"CONTAINER_NAME": info.Name(),
"CONTAINER_TAG": tag,
}
extraAttrs := ctx.ExtraAttributes(sanitizeKeyMod)
extraAttrs := info.ExtraAttributes(sanitizeKeyMod)
for k, v := range extraAttrs {
vars[k] = v
}

View file

@ -40,9 +40,9 @@ func init() {
// New creates new JSONFileLogger which writes to filename passed in
// on given context.
func New(ctx logger.Context) (logger.Logger, error) {
func New(info logger.Info) (logger.Logger, error) {
var capval int64 = -1
if capacity, ok := ctx.Config["max-size"]; ok {
if capacity, ok := info.Config["max-size"]; ok {
var err error
capval, err = units.FromHumanSize(capacity)
if err != nil {
@ -50,7 +50,7 @@ func New(ctx logger.Context) (logger.Logger, error) {
}
}
var maxFiles = 1
if maxFileString, ok := ctx.Config["max-file"]; ok {
if maxFileString, ok := info.Config["max-file"]; ok {
var err error
maxFiles, err = strconv.Atoi(maxFileString)
if err != nil {
@ -61,13 +61,13 @@ func New(ctx logger.Context) (logger.Logger, error) {
}
}
writer, err := loggerutils.NewRotateFileWriter(ctx.LogPath, capval, maxFiles)
writer, err := loggerutils.NewRotateFileWriter(info.LogPath, capval, maxFiles)
if err != nil {
return nil, err
}
var extra []byte
if attrs := ctx.ExtraAttributes(nil); len(attrs) > 0 {
if attrs := info.ExtraAttributes(nil); len(attrs) > 0 {
var err error
extra, err = json.Marshal(attrs)
if err != nil {

View file

@ -22,7 +22,7 @@ func TestJSONFileLogger(t *testing.T) {
}
defer os.RemoveAll(tmp)
filename := filepath.Join(tmp, "container.log")
l, err := New(logger.Context{
l, err := New(logger.Info{
ContainerID: cid,
LogPath: filename,
})
@ -62,7 +62,7 @@ func BenchmarkJSONFileLogger(b *testing.B) {
}
defer os.RemoveAll(tmp)
filename := filepath.Join(tmp, "container.log")
l, err := New(logger.Context{
l, err := New(logger.Info{
ContainerID: cid,
LogPath: filename,
})
@ -97,7 +97,7 @@ func TestJSONFileLoggerWithOpts(t *testing.T) {
defer os.RemoveAll(tmp)
filename := filepath.Join(tmp, "container.log")
config := map[string]string{"max-file": "2", "max-size": "1k"}
l, err := New(logger.Context{
l, err := New(logger.Info{
ContainerID: cid,
LogPath: filename,
Config: config,
@ -161,7 +161,7 @@ func TestJSONFileLoggerWithLabelsEnv(t *testing.T) {
defer os.RemoveAll(tmp)
filename := filepath.Join(tmp, "container.log")
config := map[string]string{"labels": "rack,dc", "env": "environ,debug,ssl"}
l, err := New(logger.Context{
l, err := New(logger.Info{
ContainerID: cid,
LogPath: filename,
Config: config,
@ -210,7 +210,7 @@ func BenchmarkJSONFileLoggerWithReader(b *testing.B) {
}
defer os.RemoveAll(dir)
l, err := New(logger.Context{
l, err := New(logger.Info{
ContainerID: cid,
LogPath: filepath.Join(dir, "container.log"),
})

View file

@ -35,18 +35,18 @@ func init() {
// New creates a logentries logger using the configuration passed in on
// the context. The supported context configuration variable is
// logentries-token.
func New(ctx logger.Context) (logger.Logger, error) {
logrus.WithField("container", ctx.ContainerID).
WithField("token", ctx.Config[token]).
func New(info logger.Info) (logger.Logger, error) {
logrus.WithField("container", info.ContainerID).
WithField("token", info.Config[token]).
Debug("logging driver logentries configured")
log, err := le_go.Connect(ctx.Config[token])
log, err := le_go.Connect(info.Config[token])
if err != nil {
return nil, err
}
return &logentries{
containerID: ctx.ContainerID,
containerName: ctx.ContainerName,
containerID: info.ContainerID,
containerName: info.ContainerName,
writer: log,
}, nil
}

View file

@ -12,8 +12,8 @@ const DefaultTemplate = "{{.ID}}"
// ParseLogTag generates a context aware tag for consistency across different
// log drivers based on the context of the running container.
func ParseLogTag(ctx logger.Context, defaultTemplate string) (string, error) {
tagTemplate := ctx.Config["tag"]
func ParseLogTag(info logger.Info, defaultTemplate string) (string, error) {
tagTemplate := info.Config["tag"]
if tagTemplate == "" {
tagTemplate = defaultTemplate
}
@ -23,7 +23,7 @@ func ParseLogTag(ctx logger.Context, defaultTemplate string) (string, error) {
return "", err
}
buf := new(bytes.Buffer)
if err := tmpl.Execute(buf, &ctx); err != nil {
if err := tmpl.Execute(buf, &info); err != nil {
return "", err
}

View file

@ -7,27 +7,27 @@ import (
)
func TestParseLogTagDefaultTag(t *testing.T) {
ctx := buildContext(map[string]string{})
tag, e := ParseLogTag(ctx, "{{.ID}}")
assertTag(t, e, tag, ctx.ID())
info := buildContext(map[string]string{})
tag, e := ParseLogTag(info, "{{.ID}}")
assertTag(t, e, tag, info.ID())
}
func TestParseLogTag(t *testing.T) {
ctx := buildContext(map[string]string{"tag": "{{.ImageName}}/{{.Name}}/{{.ID}}"})
tag, e := ParseLogTag(ctx, "{{.ID}}")
info := buildContext(map[string]string{"tag": "{{.ImageName}}/{{.Name}}/{{.ID}}"})
tag, e := ParseLogTag(info, "{{.ID}}")
assertTag(t, e, tag, "test-image/test-container/container-ab")
}
func TestParseLogTagEmptyTag(t *testing.T) {
ctx := buildContext(map[string]string{})
tag, e := ParseLogTag(ctx, "{{.DaemonName}}/{{.ID}}")
info := buildContext(map[string]string{})
tag, e := ParseLogTag(info, "{{.DaemonName}}/{{.ID}}")
assertTag(t, e, tag, "test-dockerd/container-ab")
}
// Helpers
func buildContext(cfg map[string]string) logger.Context {
return logger.Context{
func buildContext(cfg map[string]string) logger.Info {
return logger.Info{
ContainerID: "container-abcdefghijklmnopqrstuvwxyz01234567890",
ContainerName: "/test-container",
ContainerImageID: "image-abcdefghijklmnopqrstuvwxyz01234567890",

View file

@ -7,8 +7,8 @@ import (
"time"
)
// Context provides enough information for a logging driver to do its function.
type Context struct {
// Info provides enough information for a logging driver to do its function.
type Info struct {
Config map[string]string
ContainerID string
ContainerName string
@ -26,12 +26,12 @@ type Context struct {
// ExtraAttributes returns the user-defined extra attributes (labels,
// environment variables) in key-value format. This can be used by log drivers
// that support metadata to add more context to a log.
func (ctx *Context) ExtraAttributes(keyMod func(string) string) map[string]string {
func (info *Info) ExtraAttributes(keyMod func(string) string) map[string]string {
extra := make(map[string]string)
labels, ok := ctx.Config["labels"]
labels, ok := info.Config["labels"]
if ok && len(labels) > 0 {
for _, l := range strings.Split(labels, ",") {
if v, ok := ctx.ContainerLabels[l]; ok {
if v, ok := info.ContainerLabels[l]; ok {
if keyMod != nil {
l = keyMod(l)
}
@ -40,10 +40,10 @@ func (ctx *Context) ExtraAttributes(keyMod func(string) string) map[string]strin
}
}
env, ok := ctx.Config["env"]
env, ok := info.Config["env"]
if ok && len(env) > 0 {
envMapping := make(map[string]string)
for _, e := range ctx.ContainerEnv {
for _, e := range info.ContainerEnv {
if kv := strings.SplitN(e, "=", 2); len(kv) == 2 {
envMapping[kv[0]] = kv[1]
}
@ -62,7 +62,7 @@ func (ctx *Context) ExtraAttributes(keyMod func(string) string) map[string]strin
}
// Hostname returns the hostname from the underlying OS.
func (ctx *Context) Hostname() (string, error) {
func (info *Info) Hostname() (string, error) {
hostname, err := os.Hostname()
if err != nil {
return "", fmt.Errorf("logger: can not resolve hostname: %v", err)
@ -73,39 +73,39 @@ func (ctx *Context) Hostname() (string, error) {
// Command returns the command that the container being logged was
// started with. The Entrypoint is prepended to the container
// arguments.
func (ctx *Context) Command() string {
terms := []string{ctx.ContainerEntrypoint}
terms = append(terms, ctx.ContainerArgs...)
func (info *Info) Command() string {
terms := []string{info.ContainerEntrypoint}
terms = append(terms, info.ContainerArgs...)
command := strings.Join(terms, " ")
return command
}
// ID Returns the Container ID shortened to 12 characters.
func (ctx *Context) ID() string {
return ctx.ContainerID[:12]
func (info *Info) ID() string {
return info.ContainerID[:12]
}
// FullID is an alias of ContainerID.
func (ctx *Context) FullID() string {
return ctx.ContainerID
func (info *Info) FullID() string {
return info.ContainerID
}
// Name returns the ContainerName without a preceding '/'.
func (ctx *Context) Name() string {
return strings.TrimPrefix(ctx.ContainerName, "/")
func (info *Info) Name() string {
return strings.TrimPrefix(info.ContainerName, "/")
}
// ImageID returns the ContainerImageID shortened to 12 characters.
func (ctx *Context) ImageID() string {
return ctx.ContainerImageID[:12]
func (info *Info) ImageID() string {
return info.ContainerImageID[:12]
}
// ImageFullID is an alias of ContainerImageID.
func (ctx *Context) ImageFullID() string {
return ctx.ContainerImageID
func (info *Info) ImageFullID() string {
return info.ContainerImageID
}
// ImageName is an alias of ContainerImageName
func (ctx *Context) ImageName() string {
return ctx.ContainerImageName
func (info *Info) ImageName() string {
return info.ContainerImageName
}

View file

@ -140,20 +140,20 @@ func init() {
}
// New creates splunk logger driver using configuration passed in context
func New(ctx logger.Context) (logger.Logger, error) {
hostname, err := ctx.Hostname()
func New(info logger.Info) (logger.Logger, error) {
hostname, err := info.Hostname()
if err != nil {
return nil, fmt.Errorf("%s: cannot access hostname to set source field", driverName)
}
// Parse and validate Splunk URL
splunkURL, err := parseURL(ctx)
splunkURL, err := parseURL(info)
if err != nil {
return nil, err
}
// Splunk Token is required parameter
splunkToken, ok := ctx.Config[splunkTokenKey]
splunkToken, ok := info.Config[splunkTokenKey]
if !ok {
return nil, fmt.Errorf("%s: %s is expected", driverName, splunkTokenKey)
}
@ -162,7 +162,7 @@ func New(ctx logger.Context) (logger.Logger, error) {
// Splunk is using autogenerated certificates by default,
// allow users to trust them with skipping verification
if insecureSkipVerifyStr, ok := ctx.Config[splunkInsecureSkipVerifyKey]; ok {
if insecureSkipVerifyStr, ok := info.Config[splunkInsecureSkipVerifyKey]; ok {
insecureSkipVerify, err := strconv.ParseBool(insecureSkipVerifyStr)
if err != nil {
return nil, err
@ -171,7 +171,7 @@ func New(ctx logger.Context) (logger.Logger, error) {
}
// If path to the root certificate is provided - load it
if caPath, ok := ctx.Config[splunkCAPathKey]; ok {
if caPath, ok := info.Config[splunkCAPathKey]; ok {
caCert, err := ioutil.ReadFile(caPath)
if err != nil {
return nil, err
@ -181,12 +181,12 @@ func New(ctx logger.Context) (logger.Logger, error) {
tlsConfig.RootCAs = caPool
}
if caName, ok := ctx.Config[splunkCANameKey]; ok {
if caName, ok := info.Config[splunkCANameKey]; ok {
tlsConfig.ServerName = caName
}
gzipCompression := false
if gzipCompressionStr, ok := ctx.Config[splunkGzipCompressionKey]; ok {
if gzipCompressionStr, ok := info.Config[splunkGzipCompressionKey]; ok {
gzipCompression, err = strconv.ParseBool(gzipCompressionStr)
if err != nil {
return nil, err
@ -194,7 +194,7 @@ func New(ctx logger.Context) (logger.Logger, error) {
}
gzipCompressionLevel := gzip.DefaultCompression
if gzipCompressionLevelStr, ok := ctx.Config[splunkGzipCompressionLevelKey]; ok {
if gzipCompressionLevelStr, ok := info.Config[splunkGzipCompressionLevelKey]; ok {
var err error
gzipCompressionLevel64, err := strconv.ParseInt(gzipCompressionLevelStr, 10, 32)
if err != nil {
@ -215,9 +215,9 @@ func New(ctx logger.Context) (logger.Logger, error) {
Transport: transport,
}
source := ctx.Config[splunkSourceKey]
sourceType := ctx.Config[splunkSourceTypeKey]
index := ctx.Config[splunkIndexKey]
source := info.Config[splunkSourceKey]
sourceType := info.Config[splunkSourceTypeKey]
index := info.Config[splunkIndexKey]
var nullMessage = &splunkMessage{
Host: hostname,
@ -228,14 +228,14 @@ func New(ctx logger.Context) (logger.Logger, error) {
// Allow user to remove tag from the messages by setting tag to empty string
tag := ""
if tagTemplate, ok := ctx.Config[tagKey]; !ok || tagTemplate != "" {
tag, err = loggerutils.ParseLogTag(ctx, loggerutils.DefaultTemplate)
if tagTemplate, ok := info.Config[tagKey]; !ok || tagTemplate != "" {
tag, err = loggerutils.ParseLogTag(info, loggerutils.DefaultTemplate)
if err != nil {
return nil, err
}
}
attrs := ctx.ExtraAttributes(nil)
attrs := info.ExtraAttributes(nil)
var (
postMessagesFrequency = getAdvancedOptionDuration(envVarPostMessagesFrequency, defaultPostMessagesFrequency)
@ -260,7 +260,7 @@ func New(ctx logger.Context) (logger.Logger, error) {
// By default we verify connection, but we allow use to skip that
verifyConnection := true
if verifyConnectionStr, ok := ctx.Config[splunkVerifyConnectionKey]; ok {
if verifyConnectionStr, ok := info.Config[splunkVerifyConnectionKey]; ok {
var err error
verifyConnection, err = strconv.ParseBool(verifyConnectionStr)
if err != nil {
@ -275,7 +275,7 @@ func New(ctx logger.Context) (logger.Logger, error) {
}
var splunkFormat string
if splunkFormatParsed, ok := ctx.Config[splunkFormatKey]; ok {
if splunkFormatParsed, ok := info.Config[splunkFormatKey]; ok {
switch splunkFormatParsed {
case splunkFormatInline:
case splunkFormatJSON:
@ -547,8 +547,8 @@ func ValidateLogOpt(cfg map[string]string) error {
return nil
}
func parseURL(ctx logger.Context) (*url.URL, error) {
splunkURLStr, ok := ctx.Config[splunkURLKey]
func parseURL(info logger.Info) (*url.URL, error) {
splunkURLStr, ok := info.Config[splunkURLKey]
if !ok {
return nil, fmt.Errorf("%s: %s is expected", driverName, splunkURLKey)
}

View file

@ -43,10 +43,10 @@ func TestValidateLogOpt(t *testing.T) {
// Driver require user to specify required options
func TestNewMissedConfig(t *testing.T) {
ctx := logger.Context{
info := logger.Info{
Config: map[string]string{},
}
_, err := New(ctx)
_, err := New(info)
if err == nil {
t.Fatal("Logger driver should fail when no required parameters specified")
}
@ -54,12 +54,12 @@ func TestNewMissedConfig(t *testing.T) {
// Driver require user to specify splunk-url
func TestNewMissedUrl(t *testing.T) {
ctx := logger.Context{
info := logger.Info{
Config: map[string]string{
splunkTokenKey: "4642492F-D8BD-47F1-A005-0C08AE4657DF",
},
}
_, err := New(ctx)
_, err := New(info)
if err.Error() != "splunk: splunk-url is expected" {
t.Fatal("Logger driver should fail when no required parameters specified")
}
@ -67,12 +67,12 @@ func TestNewMissedUrl(t *testing.T) {
// Driver require user to specify splunk-token
func TestNewMissedToken(t *testing.T) {
ctx := logger.Context{
info := logger.Info{
Config: map[string]string{
splunkURLKey: "http://127.0.0.1:8088",
},
}
_, err := New(ctx)
_, err := New(info)
if err.Error() != "splunk: splunk-token is expected" {
t.Fatal("Logger driver should fail when no required parameters specified")
}
@ -84,7 +84,7 @@ func TestDefault(t *testing.T) {
go hec.Serve()
ctx := logger.Context{
info := logger.Info{
Config: map[string]string{
splunkURLKey: hec.URL(),
splunkTokenKey: hec.token,
@ -95,12 +95,12 @@ func TestDefault(t *testing.T) {
ContainerImageName: "container_image_name",
}
hostname, err := ctx.Hostname()
hostname, err := info.Hostname()
if err != nil {
t.Fatal(err)
}
loggerDriver, err := New(ctx)
loggerDriver, err := New(info)
if err != nil {
t.Fatal(err)
}
@ -206,7 +206,7 @@ func TestInlineFormatWithNonDefaultOptions(t *testing.T) {
go hec.Serve()
ctx := logger.Context{
info := logger.Info{
Config: map[string]string{
splunkURLKey: hec.URL(),
splunkTokenKey: hec.token,
@ -227,12 +227,12 @@ func TestInlineFormatWithNonDefaultOptions(t *testing.T) {
},
}
hostname, err := ctx.Hostname()
hostname, err := info.Hostname()
if err != nil {
t.Fatal(err)
}
loggerDriver, err := New(ctx)
loggerDriver, err := New(info)
if err != nil {
t.Fatal(err)
}
@ -312,7 +312,7 @@ func TestJsonFormat(t *testing.T) {
go hec.Serve()
ctx := logger.Context{
info := logger.Info{
Config: map[string]string{
splunkURLKey: hec.URL(),
splunkTokenKey: hec.token,
@ -326,12 +326,12 @@ func TestJsonFormat(t *testing.T) {
ContainerImageName: "container_image_name",
}
hostname, err := ctx.Hostname()
hostname, err := info.Hostname()
if err != nil {
t.Fatal(err)
}
loggerDriver, err := New(ctx)
loggerDriver, err := New(info)
if err != nil {
t.Fatal(err)
}
@ -431,7 +431,7 @@ func TestRawFormat(t *testing.T) {
go hec.Serve()
ctx := logger.Context{
info := logger.Info{
Config: map[string]string{
splunkURLKey: hec.URL(),
splunkTokenKey: hec.token,
@ -443,12 +443,12 @@ func TestRawFormat(t *testing.T) {
ContainerImageName: "container_image_name",
}
hostname, err := ctx.Hostname()
hostname, err := info.Hostname()
if err != nil {
t.Fatal(err)
}
loggerDriver, err := New(ctx)
loggerDriver, err := New(info)
if err != nil {
t.Fatal(err)
}
@ -541,7 +541,7 @@ func TestRawFormatWithLabels(t *testing.T) {
go hec.Serve()
ctx := logger.Context{
info := logger.Info{
Config: map[string]string{
splunkURLKey: hec.URL(),
splunkTokenKey: hec.token,
@ -557,12 +557,12 @@ func TestRawFormatWithLabels(t *testing.T) {
},
}
hostname, err := ctx.Hostname()
hostname, err := info.Hostname()
if err != nil {
t.Fatal(err)
}
loggerDriver, err := New(ctx)
loggerDriver, err := New(info)
if err != nil {
t.Fatal(err)
}
@ -656,7 +656,7 @@ func TestRawFormatWithoutTag(t *testing.T) {
go hec.Serve()
ctx := logger.Context{
info := logger.Info{
Config: map[string]string{
splunkURLKey: hec.URL(),
splunkTokenKey: hec.token,
@ -669,12 +669,12 @@ func TestRawFormatWithoutTag(t *testing.T) {
ContainerImageName: "container_image_name",
}
hostname, err := ctx.Hostname()
hostname, err := info.Hostname()
if err != nil {
t.Fatal(err)
}
loggerDriver, err := New(ctx)
loggerDriver, err := New(info)
if err != nil {
t.Fatal(err)
}
@ -773,7 +773,7 @@ func TestBatching(t *testing.T) {
go hec.Serve()
ctx := logger.Context{
info := logger.Info{
Config: map[string]string{
splunkURLKey: hec.URL(),
splunkTokenKey: hec.token,
@ -784,7 +784,7 @@ func TestBatching(t *testing.T) {
ContainerImageName: "container_image_name",
}
loggerDriver, err := New(ctx)
loggerDriver, err := New(info)
if err != nil {
t.Fatal(err)
}
@ -839,7 +839,7 @@ func TestFrequency(t *testing.T) {
go hec.Serve()
ctx := logger.Context{
info := logger.Info{
Config: map[string]string{
splunkURLKey: hec.URL(),
splunkTokenKey: hec.token,
@ -850,7 +850,7 @@ func TestFrequency(t *testing.T) {
ContainerImageName: "container_image_name",
}
loggerDriver, err := New(ctx)
loggerDriver, err := New(info)
if err != nil {
t.Fatal(err)
}
@ -920,7 +920,7 @@ func TestOneMessagePerRequest(t *testing.T) {
go hec.Serve()
ctx := logger.Context{
info := logger.Info{
Config: map[string]string{
splunkURLKey: hec.URL(),
splunkTokenKey: hec.token,
@ -931,7 +931,7 @@ func TestOneMessagePerRequest(t *testing.T) {
ContainerImageName: "container_image_name",
}
loggerDriver, err := New(ctx)
loggerDriver, err := New(info)
if err != nil {
t.Fatal(err)
}
@ -994,7 +994,7 @@ func TestVerify(t *testing.T) {
hec.simulateServerError = true
go hec.Serve()
ctx := logger.Context{
info := logger.Info{
Config: map[string]string{
splunkURLKey: hec.URL(),
splunkTokenKey: hec.token,
@ -1005,7 +1005,7 @@ func TestVerify(t *testing.T) {
ContainerImageName: "container_image_name",
}
_, err := New(ctx)
_, err := New(info)
if err == nil {
t.Fatal("Expecting driver to fail, when server is unresponsive")
}
@ -1023,7 +1023,7 @@ func TestSkipVerify(t *testing.T) {
hec.simulateServerError = true
go hec.Serve()
ctx := logger.Context{
info := logger.Info{
Config: map[string]string{
splunkURLKey: hec.URL(),
splunkTokenKey: hec.token,
@ -1035,7 +1035,7 @@ func TestSkipVerify(t *testing.T) {
ContainerImageName: "container_image_name",
}
loggerDriver, err := New(ctx)
loggerDriver, err := New(info)
if err != nil {
t.Fatal(err)
}
@ -1105,7 +1105,7 @@ func TestBufferMaximum(t *testing.T) {
hec.simulateServerError = true
go hec.Serve()
ctx := logger.Context{
info := logger.Info{
Config: map[string]string{
splunkURLKey: hec.URL(),
splunkTokenKey: hec.token,
@ -1117,7 +1117,7 @@ func TestBufferMaximum(t *testing.T) {
ContainerImageName: "container_image_name",
}
loggerDriver, err := New(ctx)
loggerDriver, err := New(info)
if err != nil {
t.Fatal(err)
}
@ -1194,7 +1194,7 @@ func TestServerAlwaysDown(t *testing.T) {
hec.simulateServerError = true
go hec.Serve()
ctx := logger.Context{
info := logger.Info{
Config: map[string]string{
splunkURLKey: hec.URL(),
splunkTokenKey: hec.token,
@ -1206,7 +1206,7 @@ func TestServerAlwaysDown(t *testing.T) {
ContainerImageName: "container_image_name",
}
loggerDriver, err := New(ctx)
loggerDriver, err := New(info)
if err != nil {
t.Fatal(err)
}
@ -1253,7 +1253,7 @@ func TestCannotSendAfterClose(t *testing.T) {
hec := NewHTTPEventCollectorMock(t)
go hec.Serve()
ctx := logger.Context{
info := logger.Info{
Config: map[string]string{
splunkURLKey: hec.URL(),
splunkTokenKey: hec.token,
@ -1264,7 +1264,7 @@ func TestCannotSendAfterClose(t *testing.T) {
ContainerImageName: "container_image_name",
}
loggerDriver, err := New(ctx)
loggerDriver, err := New(info)
if err != nil {
t.Fatal(err)
}

View file

@ -87,30 +87,30 @@ func rfc5424microformatterWithAppNameAsTag(p syslog.Priority, hostname, tag, con
// New creates a syslog logger using the configuration passed in on
// the context. Supported context configuration variables are
// syslog-address, syslog-facility, syslog-format.
func New(ctx logger.Context) (logger.Logger, error) {
tag, err := loggerutils.ParseLogTag(ctx, loggerutils.DefaultTemplate)
func New(info logger.Info) (logger.Logger, error) {
tag, err := loggerutils.ParseLogTag(info, loggerutils.DefaultTemplate)
if err != nil {
return nil, err
}
proto, address, err := parseAddress(ctx.Config["syslog-address"])
proto, address, err := parseAddress(info.Config["syslog-address"])
if err != nil {
return nil, err
}
facility, err := parseFacility(ctx.Config["syslog-facility"])
facility, err := parseFacility(info.Config["syslog-facility"])
if err != nil {
return nil, err
}
syslogFormatter, syslogFramer, err := parseLogFormat(ctx.Config["syslog-format"], proto)
syslogFormatter, syslogFramer, err := parseLogFormat(info.Config["syslog-format"], proto)
if err != nil {
return nil, err
}
var log *syslog.Writer
if proto == secureProto {
tlsConfig, tlsErr := parseTLSConfig(ctx.Config)
tlsConfig, tlsErr := parseTLSConfig(info.Config)
if tlsErr != nil {
return nil, tlsErr
}