// Handler for aws-sdk-go that logs all requests
494493
func (l *RequestLogger) log(r *request.Request) {
	service := r.ClientInfo.ServiceName
	name := "?"
	if r.Operation != nil {
		name = r.Operation.Name
	}
	methodDescription := service + "/" + name

	glog.V(l.logLevel).Infof("AWS request: %s", methodDescription)
}
679580
func (r *Router) Handler(req *http.Request) (route *Route, h Handler, vars map[string]string) {
	var match mux.RouteMatch

	if r.mux.Match(req, &match) {
		route = r.getOrCreateRoute(match.Route, "")
		h = match.Handler.(Handler)
		vars = match.Vars
		return
	}

	if r.NotFoundHandler == nil {
		h = HandlerFunc(NotFound)
		return
	}

	h = r.NotFoundHandler
	return
}
1010744
func Handler(reg metrics.Registry) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Gather and pre-sort the metrics to avoid random listings
		var names []string
		reg.Each(func(name string, i interface{}) {
			names = append(names, name)
		})
		sort.Strings(names)

		// Aggregate all the metris into a Prometheus collector
		c := newCollector()

		for _, name := range names {
			i := reg.Get(name)

			switch m := i.(type) {
			case metrics.Counter:
				c.addCounter(name, m.Snapshot())
			case metrics.Gauge:
				c.addGauge(name, m.Snapshot())
			case metrics.GaugeFloat64:
				c.addGaugeFloat64(name, m.Snapshot())
			case metrics.Histogram:
				c.addHistogram(name, m.Snapshot())
			case metrics.Meter:
				c.addMeter(name, m.Snapshot())
			case metrics.Timer:
				c.addTimer(name, m.Snapshot())
			case metrics.ResettingTimer:
				c.addResettingTimer(name, m.Snapshot())
			default:
				log.Warn("Unknown Prometheus metric type", "type", fmt.Sprintf("%T", i))
			}
		}
		w.Header().Add("Content-Type", "text/plain")
		w.Header().Add("Content-Length", fmt.Sprint(c.buff.Len()))
		w.Write(c.buff.Bytes())
	})
}
1016055
func (h *Handler) HandleLog(e *log.Entry) error {
	h.mu.Lock()
	defer h.mu.Unlock()
	h.Entries = append(h.Entries, e)
	return nil
}
148428
func (f HandlerFunc) Log(logger_name string, level LogLevel, msg string,
	calldepth int) {
	f(logger_name, level, msg, calldepth)
}
147689
func awsHandlerLogger(req *request.Request) {
	service, name := awsServiceAndName(req)
	klog.V(4).Infof("AWS request: %s %s", service, name)
}
867444
func LoggingMiddleware(out io.Writer) MiddlewareHandlerFunc {
	return func(next HandlerFunc) HandlerFunc {
		fn := func(ctx *Context) {
			start := time.Now()
			path := ctx.Request.URL.Path

			next(ctx)

			end := time.Now()
			latency := end.Sub(start)

			clientIP := ctx.ClientIP()
			method := ctx.Request.Method
			statusCode := ctx.statusCode
			statusColor := colorForStatus(statusCode)
			methodColor := colorForMethod(method)

			fmt.Fprintf(out, "%v |%s %3d %s| %13v | %s |%s  %s %-7s %s\n",
				end.Format("2006/01/02 - 15:04:05"),
				statusColor, statusCode, reset,
				latency,
				clientIP,
				methodColor, reset, method,
				path,
			)
		}
		return fn
	}
}
240199
func (o *Options) Handler(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		initOnce.Do(func() {
			options = make(map[*http.Request]*Options)
			responded = make(map[*http.Request]bool)
		})
		mutex.Lock()
		options[r] = o
		mutex.Unlock()
		defer func() {
			mutex.Lock()
			delete(options, r)
			delete(responded, r)
			mutex.Unlock()
		}()
		handler.ServeHTTP(w, r)
	})
}
526496
func LogHandler(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		tIni := time.Now()
		rw := &responseWriter{w: w}
		next.ServeHTTP(rw, r)
		tEnd := time.Now()
		log.Printf("%v [%s] %q %v %v %v\n", r.RemoteAddr, r.Method, r.URL.String(), rw.Size(), rw.Status(), tEnd.Sub(tIni))
	}

	return http.HandlerFunc(fn)
}
128904
func (middleware *Middleware) Handler(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		context, err := middleware.Limiter.Get(r.Context(), middleware.Limiter.GetIPKey(r))
		if err != nil {
			middleware.OnError(w, r, err)
			return
		}

		w.Header().Add("X-RateLimit-Limit", strconv.FormatInt(context.Limit, 10))
		w.Header().Add("X-RateLimit-Remaining", strconv.FormatInt(context.Remaining, 10))
		w.Header().Add("X-RateLimit-Reset", strconv.FormatInt(context.Reset, 10))

		if context.Reached {
			middleware.OnLimitReached(w, r)
			return
		}

		h.ServeHTTP(w, r)
	})
}
293200
func goLogHandler(level C.int, facility *C.char, message *C.char) {
	facHeader := reflect.StringHeader{
		Data: uintptr(unsafe.Pointer(facility)),
		Len:  int(C.strlen(facility)),
	}
	facString := (*string)(unsafe.Pointer(&facHeader))

	msgHeader := reflect.StringHeader{
		Data: uintptr(unsafe.Pointer(message)),
		Len:  int(C.strlen(message)),
	}
	msgString := (*string)(unsafe.Pointer(&msgHeader))

	Log.Printf("[%s] %s", *facString, *msgString)
}
246760
func awsSession(logger *logrus.Logger) *session.Session {
	awsConfig := &aws.Config{
		CredentialsChainVerboseErrors: aws.Bool(true),
	}

	// Log AWS calls if needed
	switch logger.Level {
	case logrus.DebugLevel:
		awsConfig.LogLevel = aws.LogLevel(aws.LogDebugWithHTTPBody)
	}
	awsConfig.Logger = &logrusProxy{logger}
	sess, sessionErr := session.NewSession(awsConfig)
	if sessionErr != nil {
		logger.WithField("Error", sessionErr).Warn("Failed to attach AWS Session logger")
	} else {
		sess.Handlers.Send.PushFront(func(r *request.Request) {
			logger.WithFields(logrus.Fields{
				"Service":   r.ClientInfo.ServiceName,
				"Operation": r.Operation.Name,
				"Method":    r.Operation.HTTPMethod,
				"Path":      r.Operation.HTTPPath,
				"Payload":   r.Params,
			}).Debug("AWS Request")
		})
	}
	return sess
}
1319529
func (b *MultiHandler) Handle(rec *Record) {
	wg := sync.WaitGroup{}
	wg.Add(len(b.handlers))
	for _, handler := range b.handlers {
		go func(handler Handler) {
			handler.Handle(rec)
			wg.Done()
		}(handler)
	}
	wg.Wait()
}
113579
func (mux *Mux) handler() *handler {
	return &handler{
		mux: mux,
		c:   make(chan net.Conn),
	}
}
767439
func (g *Gatekeeper) Listen() error {
	mux := bone.New()

	mux.Post("/v0/machine/aws", routes.AWSBootstrapRoute(g.defaults.Org, g.defaults.Team, g.api))

	g.s.Handler = loggingHandler(mux)
	h := httpdown.HTTP{}

	var err error
	g.hd, err = h.ListenAndServe(g.s)
	if err != nil {
		return err
	}

	return g.hd.Wait()
}
1018222
func Handler(w http.ResponseWriter, r *http.Request) {
	values := r.URL.Query()
	for _, c := range []string{"1", "true"} {
		if values.Get("pp") == c {
			prettyPrint = true
		}
	}

	var jsonBytes []byte
	var jsonErr error
	if prettyPrint {
		jsonBytes, jsonErr = json.MarshalIndent(GetStats(), "", "  ")
	} else {
		jsonBytes, jsonErr = json.Marshal(GetStats())
	}
	var body string
	if jsonErr != nil {
		body = jsonErr.Error()
	} else {
		body = string(jsonBytes)
	}

	if newLineTerm {
		body += "\n"
	}

	headers := make(map[string]string)
	headers["Content-Type"] = "application/json"
	headers["Content-Length"] = strconv.Itoa(len(body))
	for name, value := range headers {
		w.Header().Set(name, value)
	}

	if jsonErr != nil {
		w.WriteHeader(http.StatusInternalServerError)
	} else {
		w.WriteHeader(http.StatusOK)
	}

	io.WriteString(w, body)
}
1366042
func Logs(c *deis.Client, appID string, lines int) (string, error) {
	u := fmt.Sprintf("/v2/apps/%s/logs", appID)

	if lines > 0 {
		u += "?log_lines=" + strconv.Itoa(lines)
	}

	res, reqErr := c.Request("GET", u, nil)
	if reqErr != nil && !deis.IsErrAPIMismatch(reqErr) {
		return "", ErrNoLogs
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil || len(body) < 3 {
		return "", ErrNoLogs
	}

	// We need to trim a few characters off the front and end of the string
	return string(body), reqErr
}