// ApplyFormatter calls ApplyFormatter on every formatter
974239
func (formatters FormatterArray) ApplyFormatter(msg *Message) error {
	for _, formatter := range formatters {
		if formatter.CanBeApplied(msg) {
			if err := formatter.ApplyFormatter(msg); err != nil {
				return err
			}
		}
	}
	return nil
}
251084
func (logger *Logger) SetFormatter(formatter lg.Formatter) {
	unsafeStd := (*unsafe.Pointer)(unsafe.Pointer(&logger.std))
	old := logger.std
	logger.std.Formatter = formatter
	atomic.CompareAndSwapPointer(unsafeStd, unsafe.Pointer(old), unsafe.Pointer(logger.std))
}
154284
func (format *JSONToInflux10) ApplyFormatter(msg *core.Message) error {
	content := format.GetAppliedContent(msg)

	values := make(tcontainer.MarshalMap)
	err := json.Unmarshal(content, &values)

	if err != nil {
		format.Logger.Warningf("JSON parser error: %s, Message: %s", err, content)
		return err
	}

	var timestamp int64
	if val, ok := values[format.timeField]; ok {
		timestamp, err = format.toUnixTime(val.(string))
		if err != nil {
			format.Logger.Error("Invalid time format in message:", err)
		}
		delete(values, format.timeField)
	} else {
		timestamp = time.Now().Unix()
	}

	measurement, measurementFound := values[format.measurement]
	if !measurementFound {
		return fmt.Errorf("required field for measurement (%s) not found in payload", format.measurement)
	}

	delete(values, format.measurement)

	fields := make(map[string]interface{})
	tags := make(map[string]interface{})
	for k, v := range values {
		if _, ignore := format.ignore[k]; ignore {
			continue
		}
		key := format.escapeMetadata(k)
		if _, isTag := format.tags[k]; isTag {
			tags[key] = format.escapeMetadata(v.(string))
		} else {
			fields[key] = format.escapeFieldValue(v.(string))
		}
	}

	measurementString := format.escapeMeasurement(measurement.(string))

	tagsString := format.joinMap(tags)
	if len(tagsString) > 0 {
		// Only add comma between measurement and tags if tags are not empty.
		// See https://docs.influxdata.com/influxdb/v1.2/write_protocols/line_protocol_reference/
		tagsString = "," + tagsString
	}

	fieldsString := format.joinMap(fields)

	line := fmt.Sprintf(
		`%s%s %s %d`,
		measurementString,
		tagsString,
		fieldsString,
		timestamp)

	format.SetAppliedContent(msg, []byte(line))
	return nil
}
666448
func (s *ImportJobRequest) SetFormat(v string) *ImportJobRequest {
	s.Format = &v
	return s
}
1017076
func (c *templateContext) applyTransformations(n parse.Node) (bool, error) {
	switch x := n.(type) {
	case *parse.ListNode:
		if x != nil {
			c.applyTransformationsToNodes(x.Nodes...)
		}
	case *parse.ActionNode:
		c.applyTransformationsToNodes(x.Pipe)
	case *parse.IfNode:
		c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList)
		c.wrapWithGetIf(x.Pipe)
	case *parse.WithNode:
		c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList)
		c.wrapWithGetIf(x.Pipe)
	case *parse.RangeNode:
		c.applyTransformationsToNodes(x.Pipe, x.List, x.ElseList)
	case *parse.TemplateNode:
		subTempl := c.getIfNotVisited(x.Name)
		if subTempl != nil {
			c.applyTransformationsToNodes(subTempl.Root)
		}
	case *parse.PipeNode:
		c.collectConfig(x)
		if len(x.Decl) == 1 && len(x.Cmds) == 1 {
			// maps $site => .Site etc.
			c.decl[x.Decl[0].Ident[0]] = x.Cmds[0].String()
		}

		for i, cmd := range x.Cmds {
			keep, _ := c.applyTransformations(cmd)
			if !keep {
				x.Cmds = append(x.Cmds[:i], x.Cmds[i+1:]...)
			}
		}

	case *parse.CommandNode:
		c.collectInner(x)
		keep := c.collectReturnNode(x)

		for _, elem := range x.Args {
			switch an := elem.(type) {
			case *parse.FieldNode:
				c.updateIdentsIfNeeded(an.Ident)
			case *parse.VariableNode:
				c.updateIdentsIfNeeded(an.Ident)
			case *parse.PipeNode:
				c.applyTransformations(an)
			case *parse.ChainNode:
				// site.Params...
				if len(an.Field) > 1 && an.Field[0] == paramsIdentifier {
					c.updateIdentsIfNeeded(an.Field)
				}
			}
		}
		return keep, c.err
	}

	return true, c.err
}
28310
func MakePlainFormatter() MessageFormatter {
	return func(m message.Composer) (string, error) {
		return m.String(), nil
	}
}
608496
func (self *Server) applyTemplate(
	w http.ResponseWriter,
	req *http.Request,
	requestPath string,
	data []byte,
	header *TemplateHeader,
	urlParams map[string]interface{},
	mimeType string,
) error {
	fragments := make(FragmentSet, 0)
	forceSkipLayout := false
	layouts := make([]string, 0)

	// start building headers stack and calculate line offsets (for error reporting)
	if header != nil {
		if header.Layout != `` {
			if header.Layout == `false` || header.Layout == `none` {
				forceSkipLayout = true
			} else {
				layouts = []string{header.Layout}
			}
		}

		// add all includes from the current item
		if err := self.appendIncludes(&fragments, header); err != nil {
			return err
		}
	}

	// get a reference to a set of standard functions that won't have a scope yet
	earlyFuncs := self.GetTemplateFunctions(requestToEvalData(req, header))

	// only process layouts if we're supposed to
	if self.EnableLayouts && !forceSkipLayout && self.shouldApplyLayout(requestPath) {
		// files starting with "_" are partials and should not have layouts applied
		if !strings.HasPrefix(path.Base(requestPath), `_`) {
			// if no layouts were explicitly specified, and a layout named "default" exists, add it to the list
			if len(layouts) == 0 {
				if _, err := self.LoadLayout(`default`); err == nil {
					layouts = append(layouts, `default`)
				}
			}

			if len(layouts) > 0 {
				for _, layoutName := range layouts {
					layoutName = EvalInline(layoutName, nil, earlyFuncs)

					if layoutFile, err := self.LoadLayout(layoutName); err == nil {
						if err := fragments.Parse(LayoutTemplateName, layoutFile); err != nil {
							return err
						}

						break
					} else if layoutName != `default` {
						// we don't care if the default layout is missing
						return err
					}
				}
			}
		}
	}

	// get the content template in place
	// NOTE: make SURE this happens after the layout is loaded. this ensures that the layout data
	//       and bindings are evaluated first, then are overridden/appended by the content data/bindings
	if err := fragments.Set(ContentTemplateName, header, data); err != nil {
		return err
	}

	// get the merged header from all layouts, includes, and the template we're rendering
	finalHeader := fragments.Header(self)

	// add all includes
	if err := self.appendIncludes(&fragments, &finalHeader); err != nil {
		return err
	}

	// put any url route params in there too
	finalHeader.UrlParams = urlParams

	if funcs, data, err := self.GetTemplateData(req, &finalHeader); err == nil {
		start := time.Now()

		// switches allow the template processing to be hijacked/redirected mid-evaluation
		// based on data already evaluated
		if len(finalHeader.Switch) > 0 {
			for i, swcase := range finalHeader.Switch {
				if swcase == nil {
					continue
				}

				if swcase.UsePath != `` {
					// if a condition is specified, it must evalutate to a truthy value to proceed
					if swcase.Condition != `` {
						if !typeutil.V(EvalInline(swcase.Condition, data, funcs)).Bool() {
							continue
						}
					}

					if swTemplate, err := self.fs.Open(swcase.UsePath); err == nil {
						if swHeader, swData, err := SplitTemplateHeaderContent(swTemplate); err == nil {
							finalHeader.Switch[i] = nil

							if fh, err := finalHeader.Merge(swHeader); err == nil {
								log.Debugf("[%s] Switch case %d matched, switching to template %v", reqid(req), i, swcase.UsePath)
								// log.Dump(fh)

								return self.applyTemplate(
									w,
									req,
									requestPath,
									swData,
									fh,
									urlParams,
									mimeType,
								)
							} else {
								return err
							}
						} else {
							return err
						}
					} else {
						return err
					}
				}
			}
		}

		var postTemplateRenderer Renderer
		var renderOpts = RenderOptions{
			FunctionSet:   funcs,
			Header:        &finalHeader,
			Fragments:     fragments,
			Data:          data,
			MimeType:      mimeType,
			RequestedPath: requestPath,
		}

		// if specified, get the FINAL renderer that the template output will be passed to
		finalHeader.Renderer = EvalInline(finalHeader.Renderer, data, funcs)

		switch finalHeader.Renderer {
		case ``, `html`:
			if r, ok := GetRendererForFilename(requestPath, self); ok {
				postTemplateRenderer = r
			}
		default:
			if r, err := GetRenderer(finalHeader.Renderer, self); err == nil {
				postTemplateRenderer = r
			} else {
				return err
			}
		}

		// evaluate and render the template first
		if baseRenderer, err := GetRenderer(``, self); err == nil {
			// if a user-specified renderer was provided, take the rendered output and
			// pass it into that renderer.  return the result
			if postTemplateRenderer != nil {
				var err error

				if postTemplateRenderer.ShouldPrerender() || httputil.QBool(req, `__subrender`) {
					// we use an httptest.ResponseRecorder to intercept the default template's output
					// and pass it as input to the final renderer.
					intercept := httptest.NewRecorder()

					err = baseRenderer.Render(intercept, req, renderOpts)
					res := intercept.Result()
					renderOpts.MimeType = res.Header.Get(`Content-Type`)
					renderOpts.Input = res.Body
				}

				if err == nil {
					// run the final template render and return
					log.Debugf("[%s] Rendering using %T", reqid(req), postTemplateRenderer)

					postTemplateRenderer.SetPrewriteFunc(func(r *http.Request) {
						reqtime(r, `tpl`, time.Since(start))
						writeRequestTimerHeaders(w, r)
					})

					return postTemplateRenderer.Render(w, req, renderOpts)
				} else {
					return err
				}
			} else {
				// just render the base template directly to the response and return

				baseRenderer.SetPrewriteFunc(func(r *http.Request) {
					reqtime(r, `tpl`, time.Since(start))
					writeRequestTimerHeaders(w, r)
				})

				return baseRenderer.Render(w, req, renderOpts)
			}
		} else {
			return err
		}
	} else if redir, ok := err.(RedirectTo); ok {
		log.Infof("[%s] Performing 307 Temporary Redirect to %v due to binding response handler.", reqid(req), redir)
		writeRequestTimerHeaders(w, req)
		http.Redirect(w, req, redir.Error(), http.StatusTemporaryRedirect)
		return nil
	} else {
		return err
	}
}
869813
func (serviceMap *ServiceMap) apply(changes *ServiceChangeTracker, UDPStaleClusterIP sets.String) {
	changes.lock.Lock()
	defer changes.lock.Unlock()
	for _, change := range changes.items {
		serviceMap.merge(change.current)
		// filter out the Update event of current changes from previous changes before calling unmerge() so that can
		// skip deleting the Update events.
		change.previous.filter(change.current)
		serviceMap.unmerge(change.previous, UDPStaleClusterIP)
	}
	// clear changes after applying them to ServiceMap.
	changes.items = make(map[types.NamespacedName]*serviceChange)
	return
}
987433
func (f *Int64SliceFlag) Apply(set *flag.FlagSet) {
	f.set = set
	f.Int64SliceFlag.Apply(set)
}
1155417
func (format *Base64Encode) ApplyFormatter(msg *core.Message) error {
	encoded := format.getEncodedContent(format.GetAppliedContent(msg))
	format.SetAppliedContent(msg, encoded)

	return nil
}
296078
func (format *StreamName) ApplyFormatter(msg *core.Message) error {
	streamName := format.getStreamName(msg)
	content := format.GetAppliedContent(msg)

	dataSize := len(streamName) + len(format.separator) + len(content)
	payload := make([]byte, dataSize)

	offset := copy(payload, []byte(streamName))
	offset += copy(payload[offset:], format.separator)
	copy(payload[offset:], content)

	format.SetAppliedContent(msg, payload)
	return nil
}
916886
func NewFormatter(verb, format string) (Formatter, error) {
	switch verb {
	case "color":
		return newColorFormatter(format)
	case "id":
		return newSequenceFormatter(format), nil
	case "level":
		return newLevelFormatter(format), nil
	case "message":
		return newMessageFormatter(format), nil
	case "module":
		return newModuleFormatter(format), nil
	case "shortfunc":
		return newShortFuncFormatter(format), nil
	case "time":
		return newTimeFormatter(format), nil
	default:
		return nil, fmt.Errorf("unknown verb: %s", verb)
	}
}
882945
func createFormatter(name string, kind string) (Formatter, error) {
	if kind == FormatEnv {
		kind = logxiFormat
	}
	if kind == "" {
		kind = FormatText
	}

	fn := formatterCreators[kind]
	if fn == nil {
		fn = formatterCreators[FormatText]
	}

	formatter, err := fn(name, kind)
	if err != nil {
		return nil, err
	}
	// custom formatter may have not returned a formatter
	if formatter == nil {
		formatter, err = formatFactory(name, FormatText)
	}
	return formatter, err
}
80575
func (format *SplitToJSON) ApplyFormatter(msg *core.Message) error {
	components := bytes.Split(format.GetAppliedContent(msg), format.token)
	maxIdx := tmath.MinI(len(format.keys), len(components))
	jsonData := ""

	switch {
	case maxIdx == 0:
	case maxIdx == 1:
		jsonData = fmt.Sprintf("{%s:\"%s\"}", format.keys[0], components[0])
	default:
		for i := 0; i < maxIdx; i++ {
			key := tstrings.EscapeJSON(format.keys[i])
			value := string(components[i])
			if isJSON, _, _ := tstrings.IsJSON(components[i]); !format.keepJSON || !isJSON {
				value = "\"" + tstrings.EscapeJSON(value) + "\""
			}

			switch {
			case i == 0:
				jsonData = fmt.Sprintf("{\"%s\":%s", key, value)
			case i == maxIdx-1:
				jsonData = fmt.Sprintf("%s,\"%s\":%s}", jsonData, key, value)
			default:
				jsonData = fmt.Sprintf("%s,\"%s\":%s", jsonData, key, value)
			}
		}
	}

	format.SetAppliedContent(msg, []byte(jsonData))
	return nil
}
556383
func (format *Base64Decode) ApplyFormatter(msg *core.Message) error {
	decoded, err := format.getDecodedContent(format.GetAppliedContent(msg))
	if err != nil {
		return err
	}

	format.SetAppliedContent(msg, decoded)
	return nil
}
1095095
func (format *StreamRoute) ApplyFormatter(msg *core.Message) error {
	content := format.GetAppliedContent(msg)
	delimiterIdx := bytes.Index(content, format.delimiter)

	switch delimiterIdx {
	case 0:
		content = content[len(format.delimiter):]
		format.SetAppliedContent(msg, content)
	case -1:
		// no prefix

	default:
		streamName := content[:delimiterIdx]
		streamMsg := core.NewMessage(nil, streamName, nil, msg.GetStreamID())

		content = content[(delimiterIdx + len(format.delimiter)):]
		format.SetAppliedContent(msg, content)

		switch result := format.streamModulators.Modulate(streamMsg); result {
		case core.ModulateResultDiscard, core.ModulateResultFallback:
			return nil // ### return, rule based early out ###
		}

		targetStreamID := core.GetStreamID(streamMsg.String())
		if msg.GetStreamID() != targetStreamID {
			msg.SetStreamID(targetStreamID)
		}
	}

	return nil
}
3622
func (f *flatFormatter) Format(format string, args ...interface{}) (n int, errno error) {
	return (*indentFormatter)(f).format(true, format, args...)
}