// LogThrottleD Throttle logging based on @format as a key, such that key would never
// occur more than @limit times per hour
//
//    LogThrottleD(5, u.ERROR, 1, "message %s", varx)
//
767357
func LogThrottleD(depth, logLvl, limit int, format string, v ...interface{}) {
	if LogLevel < logLvl {
		return
	}
	doLogThrottle(depth, logLvl, limit, format, fmt.Sprintf(format, v...))
}
581266
func throttled(threshold int64, h http.Handler) http.Handler {
	var active int64

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		current := atomic.AddInt64(&active, 1)
		defer atomic.AddInt64(&active, -1)

		if current-1 >= threshold {
			log.Warnf("Reached threshold of %d concurrent active clients", threshold)
			http.Error(w, "429 Too Many Requests", 429)
			return
		}

		h.ServeHTTP(w, r)
	})
}
598262
func (h *TextHandler) Log(logger_name string, level LogLevel, msg string,
	calldepth int) {
	h.mtx.RLock()
	output, template := h.output, h.template
	h.mtx.RUnlock()
	event := LogEvent{
		LoggerName: logger_name,
		Level:      level,
		Message:    strings.TrimRight(msg, "\n\r"),
		Timestamp:  time.Now()}
	if calldepth >= 0 {
		_, event.Filepath, event.Line, _ = runtime.Caller(calldepth + 1)
	}
	var buf bytes.Buffer
	err := template.Execute(&buf, &event)
	if err != nil {
		output.Output(level, []byte(
			fmt.Sprintf("log format template failed: %s", err)))
		return
	}
	output.Output(level, buf.Bytes())
}
279269
func (e *Endpoint) logStatusLocked(typ StatusType, code StatusCode, msg string) {
	e.Status.indexMU.Lock()
	defer e.Status.indexMU.Unlock()
	sts := &statusLogMsg{
		Status: Status{
			Code:  code,
			Msg:   msg,
			Type:  typ,
			State: e.state,
		},
		Timestamp: time.Now().UTC(),
	}
	e.Status.addStatusLog(sts)
	e.getLogger().WithFields(logrus.Fields{
		"code":                   sts.Status.Code,
		"type":                   sts.Status.Type,
		logfields.EndpointState:  sts.Status.State,
		logfields.PolicyRevision: e.policyRevision,
	}).Debug(msg)
}
53994
func (t *TxThrottler) Throttle() (result bool) {
	if !t.config.enabled {
		return false
	}
	if t.state == nil {
		panic("BUG: Throttle() called on a closed TxThrottler")
	}
	return t.state.throttle()
}
1155390
func (w *bothWriter) logAtLevel(level syslog.Priority, msg string) {
	var prefix string
	var err error

	const red = "\033[31m\033[1m"
	const yellow = "\033[33m"

	switch syslogAllowed := int(level) <= w.syslogLevel; level {
	case syslog.LOG_ERR:
		if syslogAllowed {
			err = w.Err(msg)
		}
		prefix = red + "E"
	case syslog.LOG_WARNING:
		if syslogAllowed {
			err = w.Warning(msg)
		}
		prefix = yellow + "W"
	case syslog.LOG_INFO:
		if syslogAllowed {
			err = w.Info(msg)
		}
		prefix = "I"
	case syslog.LOG_DEBUG:
		if syslogAllowed {
			err = w.Debug(msg)
		}
		prefix = "D"
	default:
		err = w.Err(fmt.Sprintf("%s (unknown logging level: %d)", msg, int(level)))
	}

	if err != nil {
		fmt.Fprintf(os.Stderr, "Failed to write to syslog: %s (%s)\n", msg, err)
	}

	var reset string
	if strings.HasPrefix(prefix, "\033") {
		reset = "\033[0m"
	}

	if int(level) <= w.stdoutLevel {
		fmt.Printf("%s%s %s %s%s\n",
			prefix,
			w.clk.Now().Format("150405"),
			path.Base(os.Args[0]),
			msg,
			reset)
	}
}
899153
func (ts *traceState) Log() {
	ts.mu.Lock()
	defer ts.mu.Unlock()
	gLogger.Println()

	// Special case: we require at least one span.
	if len(ts.spans) == 0 {
		return
	}

	// Print a banner for this trace.
	const bannerHalfLength = 45

	gLogger.Println()
	gLogger.Printf(
		"%s %s %s",
		strings.Repeat("=", bannerHalfLength),
		ts.spans[0].desc,
		strings.Repeat("=", bannerHalfLength))
	gLogger.Printf("Start time: %v", ts.spans[0].start.Format(time.RFC3339Nano))
	gLogger.Println()

	// Find the minimum start time and maximum end time of all durations.
	var minStart time.Time
	var maxEnd time.Time
	for _, s := range ts.spans {
		if !s.finished {
			continue
		}

		if minStart.IsZero() || s.start.Before(minStart) {
			minStart = s.start
		}

		if maxEnd.Before(s.end) {
			maxEnd = s.end
		}
	}

	// Bail out if something weird happened.
	//
	// TODO(jacobsa): Be more graceful.
	totalDuration := maxEnd.Sub(minStart)
	if minStart.IsZero() || maxEnd.IsZero() || totalDuration <= 0 {
		gLogger.Println("(Weird trace)")
		return
	}

	// Calculate the number of nanoseconds elapsed, as a floating point number.
	totalNs := float64(totalDuration / time.Nanosecond)

	// Log each span with some ASCII art showing its length relative to the
	// total.
	const totalNumCols float64 = 120
	for _, s := range ts.spans {
		if !s.finished {
			gLogger.Printf("(Unfinished: %s)", s.desc)
			gLogger.Println()
			continue
		}

		// Calculate the duration of the span, and its width relative to the
		// longest span.
		d := s.end.Sub(s.start)
		if d <= 0 {
			gLogger.Println("(Weird duration)")
			gLogger.Println()
			continue
		}

		durationRatio := float64(d/time.Nanosecond) / totalNs

		// We will offset the label and banner proportional to the time since the
		// start of the earliest span.
		offsetRatio := float64(s.start.Sub(minStart)/time.Nanosecond) / totalNs
		offsetChars := int(round(offsetRatio * totalNumCols))
		offsetStr := strings.Repeat(" ", offsetChars)

		// Print the description and duration.
		gLogger.Printf("%s%v", offsetStr, s.desc)
		gLogger.Printf("%s%v", offsetStr, d)

		// Print a banner showing the duration graphically.
		bannerChars := int(round(durationRatio * totalNumCols))
		var dashes string
		if bannerChars > 2 {
			dashes = strings.Repeat("-", bannerChars-2)
		}

		gLogger.Printf("%s|%s|", offsetStr, dashes)
		gLogger.Println()
	}
}
258740
func (c *ChannelLogger) Log(kvs ...interface{}) {
	if c.OnFull != nil {
		c.logNonBlocking(kvs...)
		return
	}
	c.logBlocking(kvs...)
}
893943
func (e *ErrorLogLogger) Log(keyvals ...interface{}) {
	if err := e.RootLogger.Log(keyvals...); err != nil && e.ErrHandler != nil {
		e.ErrorLogger(err).Log(keyvals...)
	}
}
21909
func (stats *LogStats) Logf(w io.Writer, params url.Values) error {
	rewrittenSQL := "[REDACTED]"
	formattedBindVars := "\"[REDACTED]\""

	if !*streamlog.RedactDebugUIQueries {
		rewrittenSQL = stats.RewrittenSQL()

		_, fullBindParams := params["full"]
		formattedBindVars = sqltypes.FormatBindVariables(
			stats.BindVariables,
			fullBindParams,
			*streamlog.QueryLogFormat == streamlog.QueryLogFormatJSON,
		)
	}

	// TODO: remove username here we fully enforce immediate caller id
	callInfo, username := stats.CallInfo()

	// Valid options for the QueryLogFormat are text or json
	var fmtString string
	switch *streamlog.QueryLogFormat {
	case streamlog.QueryLogFormatText:
		fmtString = "%v\t%v\t%v\t'%v'\t'%v'\t%v\t%v\t%.6f\t%v\t%q\t%v\t%v\t%q\t%v\t%.6f\t%.6f\t%v\t%v\t%q\t\n"
	case streamlog.QueryLogFormatJSON:
		fmtString = "{\"Method\": %q, \"CallInfo\": %q, \"Username\": %q, \"ImmediateCaller\": %q, \"Effective Caller\": %q, \"Start\": \"%v\", \"End\": \"%v\", \"TotalTime\": %.6f, \"PlanType\": %q, \"OriginalSQL\": %q, \"BindVars\": %v, \"Queries\": %v, \"RewrittenSQL\": %q, \"QuerySources\": %q, \"MysqlTime\": %.6f, \"ConnWaitTime\": %.6f, \"RowsAffected\": %v, \"ResponseSize\": %v, \"Error\": %q}\n"
	}

	_, err := fmt.Fprintf(
		w,
		fmtString,
		stats.Method,
		callInfo,
		username,
		stats.ImmediateCaller(),
		stats.EffectiveCaller(),
		stats.StartTime.Format("2006-01-02 15:04:05.000000"),
		stats.EndTime.Format("2006-01-02 15:04:05.000000"),
		stats.TotalTime().Seconds(),
		stats.PlanType,
		stats.OriginalSQL,
		formattedBindVars,
		stats.NumberOfQueries,
		rewrittenSQL,
		stats.FmtQuerySources(),
		stats.MysqlResponseTime.Seconds(),
		stats.WaitingForConnection.Seconds(),
		stats.RowsAffected,
		stats.SizeOfResponse(),
		stats.ErrorStr(),
	)
	return err
}
1200379
func (c MultiLogger) Log(keyvals ...interface{}) {
	for _, l := range c {
		if !IsDisabled(l) {
			l.Log(keyvals...)
		}
	}
}
52091
func (d *DockerHelper) LogError() {
	if !d.errStats.hasError() {
		fmt.Fprintf(os.Stderr, "[Error] %s %s\n", time.Now(), d.errStats.stats())
	}
	d.errStats = newErrorStats()
}
836986
func (d DefaultLogger) Logf(level LogLevel, format string, a ...interface{}) (n int, err error) {
	if level >= logThreshhold {
		return fmt.Fprintf(os.Stderr, prefix(level)+" "+format+"\n", a...)
	}

	return 0, nil
}
1374038
func (tl *ThrottledLogger) Warningf(format string, v ...interface{}) {
	tl.log(warningDepth, format, v...)
}
1039707
func (l *wrappedLogger) Log(k ...interface{}) error {
	if len(k)%2 == 1 {
		k = append(k, ErrMissingValue)
	}
	o := make([]string, len(k)/2)
	for i := 0; i < len(k); i += 2 {
		o[i/2] = fmt.Sprintf("%s=%q", k[i], k[i+1])
	}
	l.l.Println(strings.Join(o, " "))
	return nil
}
1091222
func (k *LoggerKit) Log(keyvals ...interface{}) error {
	k.LogTo.Log(keyvals...)
	return nil
}
976882
func (s *ApiStage) SetThrottle(v map[string]*ThrottleSettings) *ApiStage {
	s.Throttle = v
	return s
}