github.com/yrj2011/jx-test-infra@v0.0.0-20190529031832-7a2065ee98eb/prow/logrusutil/logrusutil.go (about)

     1  /*
     2  Copyright 2018 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  // Package logrusutil implements some helpers for using logrus
    18  package logrusutil
    19  
    20  import (
    21  	"github.com/sirupsen/logrus"
    22  )
    23  
    24  // DefaultFieldsFormatter wraps another logrus.Formatter, injecting
    25  // DefaultFields into each Format() call, existing fields are preserved
    26  // if they have the same key
    27  type DefaultFieldsFormatter struct {
    28  	WrappedFormatter logrus.Formatter
    29  	DefaultFields    logrus.Fields
    30  }
    31  
    32  // NewDefaultFieldsFormatter returns a DefaultFieldsFormatter,
    33  // if wrappedFormatter is nil &logrus.JSONFormatter{} will be used instead
    34  func NewDefaultFieldsFormatter(
    35  	wrappedFormatter logrus.Formatter, defaultFields logrus.Fields,
    36  ) *DefaultFieldsFormatter {
    37  	res := &DefaultFieldsFormatter{
    38  		WrappedFormatter: wrappedFormatter,
    39  		DefaultFields:    defaultFields,
    40  	}
    41  	if res.WrappedFormatter == nil {
    42  		res.WrappedFormatter = &logrus.JSONFormatter{}
    43  	}
    44  	return res
    45  }
    46  
    47  // Format implements logrus.Formatter's Format. We allocate a a new Fields
    48  // map in order to not modify the caller's Entry, as that is not a thread
    49  // safe operation.
    50  func (d *DefaultFieldsFormatter) Format(entry *logrus.Entry) ([]byte, error) {
    51  	data := make(logrus.Fields, len(entry.Data)+len(d.DefaultFields))
    52  	for k, v := range d.DefaultFields {
    53  		data[k] = v
    54  	}
    55  	for k, v := range entry.Data {
    56  		data[k] = v
    57  	}
    58  	return d.WrappedFormatter.Format(&logrus.Entry{
    59  		Logger:  entry.Logger,
    60  		Data:    data,
    61  		Time:    entry.Time,
    62  		Level:   entry.Level,
    63  		Message: entry.Message,
    64  	})
    65  }