get.porter.sh/porter@v1.3.0/pkg/portercontext/plugins.go (about)

     1  package portercontext
     2  
     3  import (
     4  	"encoding/json"
     5  
     6  	"github.com/hashicorp/go-hclog"
     7  	"go.uber.org/zap"
     8  	"go.uber.org/zap/zapcore"
     9  )
    10  
    11  // makePluginLogger creates a logger suitable for plugins to communicate with the hashicorp
    12  // go-plugin framework, using hclog to talk over stderr
    13  func (c *Context) makePluginLogger(pluginKey string, cfg LogConfiguration) zapcore.Core {
    14  	pluginLogger := zapToHclog{
    15  		hclog.New(&hclog.LoggerOptions{
    16  			Name:       pluginKey,
    17  			Output:     c.Err,
    18  			Level:      hclog.Debug,
    19  			JSONFormat: true,
    20  		}),
    21  	}
    22  
    23  	enc := zap.NewProductionEncoderConfig()
    24  	jsonEncoder := zapcore.NewJSONEncoder(enc)
    25  	censoredEncoder := &CensoredEncoder{Encoder: jsonEncoder, censoredWriter: c.censoredWriter}
    26  	return zapcore.NewCore(censoredEncoder, zapcore.AddSync(pluginLogger), cfg.Verbosity)
    27  }
    28  
    29  // Accepts zap log commands and translates them to a format that hclog understands
    30  // so that the plugin doesn't write any log messages that would cause the go plugin
    31  // framework to error out (i.e. printing directly to stderr)
    32  type zapToHclog struct {
    33  	logger hclog.Logger
    34  }
    35  
    36  func (z zapToHclog) Write(p []byte) (n int, err error) {
    37  	var entry map[string]interface{}
    38  	if err := json.Unmarshal(p, &entry); err != nil {
    39  		return 0, err
    40  	}
    41  	msg := entry["msg"].(string)
    42  
    43  	switch entry["level"].(string) {
    44  	case "error":
    45  		z.logger.Error(msg)
    46  	case "warn":
    47  		z.logger.Warn(msg)
    48  	case "debug":
    49  		z.logger.Debug(msg)
    50  	default:
    51  		z.logger.Info(msg)
    52  	}
    53  	return len(p), nil
    54  }