go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/gae/impl/prod/logger_old.go (about)

     1  // Copyright 2015 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  //go:build !go1.12
    16  // +build !go1.12
    17  
    18  package prod
    19  
    20  import (
    21  	"context"
    22  	"fmt"
    23  	"net/http"
    24  
    25  	"go.chromium.org/luci/common/logging"
    26  
    27  	"google.golang.org/appengine/log"
    28  )
    29  
    30  // useLogging adds a logging.Logger implementation to the context which logs to
    31  // appengine's log handler.
    32  func useLogging(c context.Context, req *http.Request) context.Context {
    33  	return logging.SetFactory(c, func(ic context.Context) logging.Logger {
    34  		return &loggerImpl{getAEContext(ic), ic}
    35  	})
    36  }
    37  
    38  type loggerImpl struct {
    39  	aeCtx context.Context
    40  	ic    context.Context
    41  }
    42  
    43  func (gl *loggerImpl) Debugf(format string, args ...any) {
    44  	gl.LogCall(logging.Debug, 1, format, args)
    45  }
    46  func (gl *loggerImpl) Infof(format string, args ...any) {
    47  	gl.LogCall(logging.Info, 1, format, args)
    48  }
    49  func (gl *loggerImpl) Warningf(format string, args ...any) {
    50  	gl.LogCall(logging.Warning, 1, format, args)
    51  }
    52  func (gl *loggerImpl) Errorf(format string, args ...any) {
    53  	gl.LogCall(logging.Error, 1, format, args)
    54  }
    55  
    56  // TODO(riannucci): prefix with caller's code location.
    57  func (gl *loggerImpl) LogCall(l logging.Level, calldepth int, format string, args []any) {
    58  	if gl.aeCtx == nil || !logging.IsLogging(gl.ic, l) {
    59  		return
    60  	}
    61  
    62  	var logf func(context.Context, string, ...any)
    63  	switch l {
    64  	case logging.Debug:
    65  		logf = log.Debugf
    66  	case logging.Info:
    67  		logf = log.Infof
    68  	case logging.Warning:
    69  		logf = log.Warningf
    70  
    71  	case logging.Error:
    72  		fallthrough
    73  	default:
    74  		logf = log.Errorf
    75  	}
    76  
    77  	fields := logging.GetFields(gl.ic)
    78  	if len(fields) > 0 {
    79  		logf(gl.aeCtx, "%s :: %s", fmt.Sprintf(format, args...), fields.String())
    80  	} else {
    81  		logf(gl.aeCtx, format, args...)
    82  	}
    83  }