// Copyright (c) 2016 Uber Technologies, Inc.1//2// Permission is hereby granted, free of charge, to any person obtaining a copy3// of this software and associated documentation files (the "Software"), to deal4// in the Software without restriction, including without limitation the rights5// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell6// copies of the Software, and to permit persons to whom the Software is7// furnished to do so, subject to the following conditions:8//9// The above copyright notice and this permission notice shall be included in10// all copies or substantial portions of the Software.11//12// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR13// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,14// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE15// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER16// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,17// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN18// THE SOFTWARE.1920package zap2122import (23"errors"24"fmt"25"sync"2627"go.uber.org/zap/zapcore"28)2930var (31errNoEncoderNameSpecified = errors.New("no encoder name specified")3233_encoderNameToConstructor = map[string]func(zapcore.EncoderConfig) (zapcore.Encoder, error){34"console": func(encoderConfig zapcore.EncoderConfig) (zapcore.Encoder, error) {35return zapcore.NewConsoleEncoder(encoderConfig), nil36},37"json": func(encoderConfig zapcore.EncoderConfig) (zapcore.Encoder, error) {38return zapcore.NewJSONEncoder(encoderConfig), nil39},40}41_encoderMutex sync.RWMutex42)4344// RegisterEncoder registers an encoder constructor, which the Config struct45// can then reference. By default, the "json" and "console" encoders are46// registered.47//48// Attempting to register an encoder whose name is already taken returns an49// error.50func RegisterEncoder(name string, constructor func(zapcore.EncoderConfig) (zapcore.Encoder, error)) error {51_encoderMutex.Lock()52defer _encoderMutex.Unlock()53if name == "" {54return errNoEncoderNameSpecified55}56if _, ok := _encoderNameToConstructor[name]; ok {57return fmt.Errorf("encoder already registered for name %q", name)58}59_encoderNameToConstructor[name] = constructor60return nil61}6263func newEncoder(name string, encoderConfig zapcore.EncoderConfig) (zapcore.Encoder, error) {64if encoderConfig.TimeKey != "" && encoderConfig.EncodeTime == nil {65return nil, errors.New("missing EncodeTime in EncoderConfig")66}6768_encoderMutex.RLock()69defer _encoderMutex.RUnlock()70if name == "" {71return nil, errNoEncoderNameSpecified72}73constructor, ok := _encoderNameToConstructor[name]74if !ok {75return nil, fmt.Errorf("no encoder registered for name %q", name)76}77return constructor(encoderConfig)78}798081