// LogRequests logs the requests to the embedded logger.
545447
func LogRequests(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		logger.Info(ctx, "request.start",
			"method", r.Method,
			"path", r.URL.Path,
			"user_agent", r.Header.Get("User-Agent"),
			"remote_ip", realip.RealIP(r),
		)

		h.ServeHTTP(w, r)

		logger.Info(ctx, "request.complete")
	})
}
1336765
func (api *SIMAPI) Logs(id int64, body interface{}) ([]sacloud.SIMLog, error) {
	var (
		method = "GET"
		uri    = fmt.Sprintf("%s/%d/sim/sessionlog", api.getResourceURL(), id)
	)

	res := &simLogResponse{}
	err := api.baseAPI.request(method, uri, body, res)
	if err != nil {
		return nil, err
	}
	return res.Logs, nil
}
277066
func (p *peer) RequestReceipts(reqID, cost uint64, hashes []common.Hash) error {
	p.Log().Debug("Fetching batch of receipts", "count", len(hashes))
	return sendRequest(p.rw, GetReceiptsMsg, reqID, cost, hashes)
}
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
}
1185369
func (lrt *LogRoundTripper) logRequest(original io.ReadCloser, contentType string) (io.ReadCloser, error) {
	defer original.Close()

	var bs bytes.Buffer
	_, err := io.Copy(&bs, original)
	if err != nil {
		return nil, err
	}

	// Handle request contentType
	if strings.HasPrefix(contentType, "application/json") {
		debugInfo := lrt.formatJSON(bs.Bytes())
		log.Printf("[DEBUG] OpenStack Request Body: %s", debugInfo)
	}

	return ioutil.NopCloser(strings.NewReader(bs.String())), nil
}
892902
func Logs() fibre.MiddlewareFunc {
	return func(h fibre.HandlerFunc) fibre.HandlerFunc {
		return func(c *fibre.Context) (err error) {

			err = h(c)

			ip := c.IP()
			req := c.Request()
			res := c.Response()
			num := res.Status()
			now := c.Request().Start()
			met := req.Method
			url := req.URL().Path
			log := c.Fibre().Logger().WithField("prefix", c.Fibre().Name())

			if c.Socket() != nil {
				met = "WS"
			}

			if err, ok := err.(*fibre.HTTPError); ok {
				num = err.Code()
				log = log.WithFields(err.Fields())
			}

			log = log.WithFields(map[string]interface{}{
				"ctx":     c,
				"ip":      ip,
				"url":     url,
				"size":    res.Size(),
				"status":  num,
				"method":  met,
				"latency": time.Since(now),
			})

			if id := c.Get("id"); id != nil {
				log = log.WithField("id", id)
			}

			if err != nil {
				log = log.WithError(err)
			}

			switch {
			case num >= 500:
				log.Error("Completed request")
			case num >= 400:
				log.Warn("Completed request")
			case num >= 300:
				log.Info("Completed request")
			case num >= 200:
				log.Info("Completed request")
			default:
				log.Info("Completed request")
			}

			return err

		}
	}
}
477825
func (r *TasksService) Requests() *TasksRequestsCall {
	c := &TasksRequestsCall{s: r.s, urlParams_: make(gensupport.URLParams)}
	return c
}
1126812
func (c *Connection) log(message string, LogLevel int, logVars ...interface{}) {
	if LogLevel <= c.LogLevel {
		c.Options.log(message, LogLevel, append([]interface{}{c.remoteAddr}, logVars...)...)
	}
}
1146430
func LogRequest(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var start time.Time
		if zerolog.GlobalLevel() <= zerolog.DebugLevel {
			start = time.Now()
		}
		h.ServeHTTP(w, r)
		if zerolog.GlobalLevel() <= zerolog.DebugLevel {
			addr := r.Header.Get("X-Real-IP")
			if addr == "" {
				addr = r.Header.Get("X-Forwarded-For")
				if addr == "" {
					addr = r.RemoteAddr
				}
			}
			log.Debug().Str("method", r.Method).Str("path", r.URL.Path).Str("addr", addr).Dur("duration", time.Since(start)).Msgf("http request")
		}
		return
	})
}
725331
func getLogEntry(req *http.Request) *logrus.Entry {
	return req.Context().Value(logCtxKey).(*logrus.Entry)
}
1079820
func (m *LogRequestList) Pack() []byte {
	data := new(bytes.Buffer)
	binary.Write(data, binary.LittleEndian, m.START)
	binary.Write(data, binary.LittleEndian, m.END)
	binary.Write(data, binary.LittleEndian, m.TARGET_SYSTEM)
	binary.Write(data, binary.LittleEndian, m.TARGET_COMPONENT)
	return data.Bytes()
}
1303520
func (f *Filter) Logs(ctx context.Context) ([]*types.Log, error) {
	// If we're doing singleton block filtering, execute and return
	if f.block != (common.Hash{}) {
		header, err := f.backend.HeaderByHash(ctx, f.block)
		if err != nil {
			return nil, err
		}
		if header == nil {
			return nil, errors.New("unknown block")
		}
		return f.blockLogs(ctx, header)
	}
	// Figure out the limits of the filter range
	header, _ := f.backend.HeaderByNumber(ctx, rpc.LatestBlockNumber)
	if header == nil {
		return nil, nil
	}
	head := header.Number.Uint64()

	if f.begin == -1 {
		f.begin = int64(head)
	}
	end := uint64(f.end)
	if f.end == -1 {
		end = head
	}
	// Gather all indexed logs, and finish with non indexed ones
	var (
		logs []*types.Log
		err  error
	)
	size, sections := f.backend.BloomStatus()
	if indexed := sections * size; indexed > uint64(f.begin) {
		if indexed > end {
			logs, err = f.indexedLogs(ctx, end)
		} else {
			logs, err = f.indexedLogs(ctx, indexed-1)
		}
		if err != nil {
			return logs, err
		}
	}
	rest, err := f.unindexedLogs(ctx, end)
	logs = append(logs, rest...)
	return logs, err
}
384443
func (c *Core) handleLoginRequest(ctx context.Context, req *logical.Request) (retResp *logical.Response, retAuth *logical.Auth, retErr error) {
	defer metrics.MeasureSince([]string{"core", "handle_login_request"}, time.Now())

	req.Unauthenticated = true

	var nonHMACReqDataKeys []string
	entry := c.router.MatchingMountEntry(ctx, req.Path)
	if entry != nil {
		// Get and set ignored HMAC'd value.
		if rawVals, ok := entry.synthesizedConfigCache.Load("audit_non_hmac_request_keys"); ok {
			nonHMACReqDataKeys = rawVals.([]string)
		}
	}

	// Do an unauth check. This will cause EGP policies to be checked
	var auth *logical.Auth
	var ctErr error
	auth, _, ctErr = c.checkToken(ctx, req, true)
	if ctErr == logical.ErrPerfStandbyPleaseForward {
		return nil, nil, ctErr
	}
	if ctErr != nil {
		// If it is an internal error we return that, otherwise we
		// return invalid request so that the status codes can be correct
		var errType error
		switch ctErr {
		case ErrInternalError, logical.ErrPermissionDenied:
			errType = ctErr
		default:
			errType = logical.ErrInvalidRequest
		}

		logInput := &audit.LogInput{
			Auth:               auth,
			Request:            req,
			OuterErr:           ctErr,
			NonHMACReqDataKeys: nonHMACReqDataKeys,
		}
		if err := c.auditBroker.LogRequest(ctx, logInput, c.auditedHeaders); err != nil {
			c.logger.Error("failed to audit request", "path", req.Path, "error", err)
			return nil, nil, ErrInternalError
		}

		if errType != nil {
			retErr = multierror.Append(retErr, errType)
		}
		if ctErr == ErrInternalError {
			return nil, auth, retErr
		}
		return logical.ErrorResponse(ctErr.Error()), auth, retErr
	}

	// Create an audit trail of the request. Attach auth if it was returned,
	// e.g. if a token was provided.
	logInput := &audit.LogInput{
		Auth:               auth,
		Request:            req,
		NonHMACReqDataKeys: nonHMACReqDataKeys,
	}
	if err := c.auditBroker.LogRequest(ctx, logInput, c.auditedHeaders); err != nil {
		c.logger.Error("failed to audit request", "path", req.Path, "error", err)
		return nil, nil, ErrInternalError
	}

	// The token store uses authentication even when creating a new token,
	// so it's handled in handleRequest. It should not be reached here.
	if strings.HasPrefix(req.Path, "auth/token/") {
		c.logger.Error("unexpected login request for token backend", "request_path", req.Path)
		return nil, nil, ErrInternalError
	}

	// Route the request
	resp, routeErr := c.doRouting(ctx, req)
	if resp != nil {
		// If wrapping is used, use the shortest between the request and response
		var wrapTTL time.Duration
		var wrapFormat, creationPath string
		var sealWrap bool

		// Ensure no wrap info information is set other than, possibly, the TTL
		if resp.WrapInfo != nil {
			if resp.WrapInfo.TTL > 0 {
				wrapTTL = resp.WrapInfo.TTL
			}
			wrapFormat = resp.WrapInfo.Format
			creationPath = resp.WrapInfo.CreationPath
			sealWrap = resp.WrapInfo.SealWrap
			resp.WrapInfo = nil
		}

		if req.WrapInfo != nil {
			if req.WrapInfo.TTL > 0 {
				switch {
				case wrapTTL == 0:
					wrapTTL = req.WrapInfo.TTL
				case req.WrapInfo.TTL < wrapTTL:
					wrapTTL = req.WrapInfo.TTL
				}
			}
			if req.WrapInfo.Format != "" && wrapFormat == "" {
				wrapFormat = req.WrapInfo.Format
			}
		}

		if wrapTTL > 0 {
			resp.WrapInfo = &wrapping.ResponseWrapInfo{
				TTL:          wrapTTL,
				Format:       wrapFormat,
				CreationPath: creationPath,
				SealWrap:     sealWrap,
			}
		}
	}

	// A login request should never return a secret!
	if resp != nil && resp.Secret != nil {
		c.logger.Error("unexpected Secret response for login path", "request_path", req.Path)
		return nil, nil, ErrInternalError
	}

	// If the response generated an authentication, then generate the token
	if resp != nil && resp.Auth != nil {

		var entity *identity.Entity
		auth = resp.Auth

		mEntry := c.router.MatchingMountEntry(ctx, req.Path)

		if auth.Alias != nil &&
			mEntry != nil &&
			!mEntry.Local &&
			c.identityStore != nil {
			// Overwrite the mount type and mount path in the alias
			// information
			auth.Alias.MountType = req.MountType
			auth.Alias.MountAccessor = req.MountAccessor

			if auth.Alias.Name == "" {
				return nil, nil, fmt.Errorf("missing name in alias")
			}

			var err error

			// Fetch the entity for the alias, or create an entity if one
			// doesn't exist.
			entity, err = c.identityStore.CreateOrFetchEntity(ctx, auth.Alias)
			if err != nil {
				entity, err = possiblyForwardAliasCreation(ctx, c, err, auth, entity)
			}
			if err != nil {
				return nil, nil, err
			}
			if entity == nil {
				return nil, nil, fmt.Errorf("failed to create an entity for the authenticated alias")
			}

			if entity.Disabled {
				return nil, nil, logical.ErrPermissionDenied
			}

			auth.EntityID = entity.ID
			if auth.GroupAliases != nil {
				validAliases, err := c.identityStore.refreshExternalGroupMembershipsByEntityID(ctx, auth.EntityID, auth.GroupAliases)
				if err != nil {
					return nil, nil, err
				}
				auth.GroupAliases = validAliases
			}
		}

		// Determine the source of the login
		source := c.router.MatchingMount(ctx, req.Path)
		source = strings.TrimPrefix(source, credentialRoutePrefix)
		source = strings.Replace(source, "/", "-", -1)

		// Prepend the source to the display name
		auth.DisplayName = strings.TrimSuffix(source+auth.DisplayName, "-")

		sysView := c.router.MatchingSystemView(ctx, req.Path)
		if sysView == nil {
			c.logger.Error("unable to look up sys view for login path", "request_path", req.Path)
			return nil, nil, ErrInternalError
		}

		tokenTTL, warnings, err := framework.CalculateTTL(sysView, 0, auth.TTL, auth.Period, auth.MaxTTL, auth.ExplicitMaxTTL, time.Time{})
		if err != nil {
			return nil, nil, err
		}
		for _, warning := range warnings {
			resp.AddWarning(warning)
		}

		ns, err := namespace.FromContext(ctx)
		if err != nil {
			return nil, nil, err
		}
		_, identityPolicies, err := c.fetchEntityAndDerivedPolicies(ctx, ns, auth.EntityID)
		if err != nil {
			return nil, nil, ErrInternalError
		}

		auth.TokenPolicies = policyutil.SanitizePolicies(auth.Policies, policyutil.AddDefaultPolicy)
		allPolicies := policyutil.SanitizePolicies(append(auth.TokenPolicies, identityPolicies[ns.ID]...), policyutil.DoNotAddDefaultPolicy)

		// Prevent internal policies from being assigned to tokens. We check
		// this on auth.Policies including derived ones from Identity before
		// actually making the token.
		for _, policy := range allPolicies {
			if policy == "root" {
				return logical.ErrorResponse("auth methods cannot create root tokens"), nil, logical.ErrInvalidRequest
			}
			if strutil.StrListContains(nonAssignablePolicies, policy) {
				return logical.ErrorResponse(fmt.Sprintf("cannot assign policy %q", policy)), nil, logical.ErrInvalidRequest
			}
		}

		var registerFunc RegisterAuthFunc
		var funcGetErr error
		// Batch tokens should not be forwarded to perf standby
		if auth.TokenType == logical.TokenTypeBatch {
			registerFunc = c.RegisterAuth
		} else {
			registerFunc, funcGetErr = getAuthRegisterFunc(c)
		}
		if funcGetErr != nil {
			retErr = multierror.Append(retErr, funcGetErr)
			return nil, auth, retErr
		}

		err = registerFunc(ctx, tokenTTL, req.Path, auth)
		switch {
		case err == nil:
		case err == ErrInternalError:
			return nil, auth, err
		default:
			return logical.ErrorResponse(err.Error()), auth, logical.ErrInvalidRequest
		}

		auth.IdentityPolicies = policyutil.SanitizePolicies(identityPolicies[ns.ID], policyutil.DoNotAddDefaultPolicy)
		delete(identityPolicies, ns.ID)
		auth.ExternalNamespacePolicies = identityPolicies
		auth.Policies = allPolicies

		// Attach the display name, might be used by audit backends
		req.DisplayName = auth.DisplayName

	}

	return resp, auth, routeErr
}
372816
func (m *MockGitilesServer) Log(arg0 context.Context, arg1 *LogRequest) (*LogResponse, error) {
	ret := m.ctrl.Call(m, "Log", arg0, arg1)
	ret0, _ := ret[0].(*LogResponse)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
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)
}
1125029
func AppLogs(appID string, lines int) error {
	c, appID, err := load(appID)

	if err != nil {
		return err
	}

	logs, err := apps.Logs(c, appID, lines)

	if err != nil {
		return err
	}

	return printLogs(logs)
}
775067
func (o LogsOptions) RunLogs() error {
	builder := o.Builder

	var requests []*logRequest

	var errs []error
	result := builder.ContinueOnError().Flatten().Do()
	err := result.Visit(func(info *resource.Info, err error) error {
		if err != nil {
			requests = append(requests, &logRequest{node: info.Name, err: err})
			return nil
		}
		mapping := info.ResourceMapping()
		client, err := o.RESTClientGetter(mapping)
		if err != nil {
			requests = append(requests, &logRequest{node: info.Name, err: err})
			return nil
		}
		path := client.Get().
			Namespace(info.Namespace).Name(info.Name).
			Resource(mapping.Resource.Resource).SubResource("proxy", "logs").Suffix(o.Path).URL().Path
		if strings.HasSuffix(o.Path, "/") {
			path += "/"
		}

		req := client.Get().RequestURI(path).
			SetHeader("Accept", "text/plain, */*").
			SetHeader("Accept-Encoding", "gzip")
		if o.Path == "journal" {
			if len(o.UntilTime) > 0 {
				req.Param("until", o.UntilTime)
			}
			if len(o.SinceTime) > 0 {
				req.Param("since", o.SinceTime)
			}
			if len(o.Output) > 0 {
				req.Param("output", o.Output)
			}
			if len(o.Units) > 0 {
				for _, unit := range o.Units {
					req.Param("unit", unit)
				}
			}
			if len(o.Grep) > 0 {
				req.Param("grep", o.Grep)
				req.Param("case-sensitive", fmt.Sprintf("%t", o.GrepCaseSensitive))
			}
			if o.Tail > 0 {
				req.Param("tail", strconv.Itoa(o.Tail))
			}
		}

		requests = append(requests, &logRequest{
			node: info.Name,
			req:  req,
			raw:  o.Raw || o.Path == "journal",
		})
		return nil
	})
	if err != nil {
		if agg, ok := err.(errors.Aggregate); ok {
			errs = append(errs, agg.Errors()...)
		} else {
			errs = append(errs, err)
		}
	}

	found := len(errs) + len(requests)
	// only hide prefix if the user specified a single item
	skipPrefix := found == 1 && result.TargetsSingleItems()

	// buffer output for slightly better streaming performance
	out := bufio.NewWriterSize(o.Out, 1024*16)
	defer out.Flush()

	if o.Unify {
		// unified output is each source, interleaved in lexographic order (assumes
		// the source input is sorted by time)
		var readers []Reader
		for i := range requests {
			req := requests[i]
			req.skipPrefix = true
			pr, pw := io.Pipe()
			readers = append(readers, Reader{
				R: pr,
			})
			go func() {
				err := req.WriteRequest(pw)
				pw.CloseWithError(err)
			}()
		}
		_, err := NewMergeReader(readers...).WriteTo(out)
		if agg := errors.Flatten(errors.NewAggregate([]error{err})); agg != nil {
			errs = append(errs, agg.Errors()...)
		}

	} else {
		// display files sequentially
		for _, req := range requests {
			req.skipPrefix = skipPrefix
			if err := req.WriteRequest(out); err != nil {
				errs = append(errs, err)
			}
		}
	}

	if len(errs) > 0 {
		for _, err := range errs {
			fmt.Fprintf(o.ErrOut, "error: %v\n", err)
		}
		return kcmdutil.ErrExit
	}

	return nil
}