func int(name string, def int64, private bool) int64 { strVal := os.Getenv(name) l := log.WithField("name", name) // No value? Use the default value provided. if strVal == "" { if !private { l = l.WithField("default", def) } l.Info("No ENV value, using default") return def } // Attempt conversion from string to an int. intVal, err := strconv.Atoi(strVal) if err != nil { if !private { l = log.WithFields(logrus.Fields{ "value": strVal, "default": def, }) } l.Error("Invalid value, using default") return def } // If we're here, it's all good. Use the new value. if !private { l = log.WithFields(logrus.Fields{ "default": def, "value": intVal, }) } l.Info("Using ENV value") return int64(intVal) }
// ServeHTTP implements the http.Handler interface and will record information // about a request, and log it after the request runs. func (logger Logger) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Retrieve the last client ip from the RemoteAddr header field. clientIP := r.RemoteAddr if colon := strings.LastIndex(clientIP, ":"); colon != -1 { clientIP = clientIP[:colon] } // Create an access log record. record := &LogRecord{ ResponseWriter: w, ip: clientIP, time: time.Now(), method: r.Method, uri: r.RequestURI, protocol: r.Proto, } // Set up a function to run once the request has been served. defer func(record *LogRecord, startTime time.Time) { // Recover from a panic if possible. if recovered := recover(); recovered != nil { var err error // Ensure we have an error interface. if thisErr, ok := recovered.(error); ok { err = thisErr } else { err = fmt.Errorf("%s", recovered) } if err != nil { log.WithError(err).Error("Recovered from panic") vc.RespondWithError(w, r, err) } } // Log the response info. finishTime := time.Now() record.time = finishTime.UTC() record.duration = finishTime.Sub(startTime) log.WithFields(record.Data()).Infof("") }(record, time.Now()) // Serve the request. logger.Handler.ServeHTTP(record, r) }