Merge pull request #18 from tmc/master

Update to use common/log
This commit is contained in:
Will Rouesnel 2016-08-06 12:46:52 +10:00 committed by GitHub
commit 39bd5d3938
11 changed files with 465 additions and 230 deletions

View File

@ -1,22 +1,19 @@
package main
import (
//"bytes"
"database/sql"
"flag"
"fmt"
"math"
"net/http"
"os"
//"regexp"
//"strconv"
//"strings"
"math"
"time"
"strconv"
_ "github.com/lib/pq"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/log"
"strconv"
"github.com/prometheus/common/log"
)
var Version string = "0.0.1"
@ -330,7 +327,7 @@ func dbToFloat64(t interface{}) (float64, bool) {
case string:
result, err := strconv.ParseFloat(v, 64)
if err != nil {
log.Println("Could not parse string:", err)
log.Infoln("Could not parse string:", err)
return math.NaN(), false
}
return result, true
@ -452,7 +449,7 @@ func (e *Exporter) scrape(ch chan<- prometheus.Metric) {
db, err := sql.Open("postgres", e.dsn)
if err != nil {
log.Println("Error opening connection to database:", err)
log.Infoln("Error opening connection to database:", err)
e.error.Set(1)
return
}
@ -498,7 +495,7 @@ func (e *Exporter) scrape(ch chan<- prometheus.Metric) {
// Don't fail on a bad scrape of one metric
rows, err := db.Query(query)
if err != nil {
log.Println("Error running query on database: ", namespace, err)
log.Infoln("Error running query on database: ", namespace, err)
e.error.Set(1)
return
}
@ -507,7 +504,7 @@ func (e *Exporter) scrape(ch chan<- prometheus.Metric) {
var columnNames []string
columnNames, err = rows.Columns()
if err != nil {
log.Println("Error retrieving column list for: ", namespace, err)
log.Infoln("Error retrieving column list for: ", namespace, err)
e.error.Set(1)
return
}
@ -527,7 +524,7 @@ func (e *Exporter) scrape(ch chan<- prometheus.Metric) {
for rows.Next() {
err = rows.Scan(scanArgs...)
if err != nil {
log.Println("Error retrieving rows:", namespace, err)
log.Infoln("Error retrieving rows:", namespace, err)
e.error.Set(1)
return
}

5
vendor/github.com/prometheus/common/NOTICE generated vendored Normal file
View File

@ -0,0 +1,5 @@
Common libraries shared by Prometheus Go components.
Copyright 2015 The Prometheus Authors
This product includes software developed at
SoundCloud Ltd. (http://soundcloud.com/).

324
vendor/github.com/prometheus/common/log/log.go generated vendored Normal file
View File

@ -0,0 +1,324 @@
// Copyright 2015 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package log
import (
"flag"
"fmt"
"log"
"net/url"
"os"
"runtime"
"strings"
"github.com/Sirupsen/logrus"
)
type levelFlag struct{}
// String implements flag.Value.
func (f levelFlag) String() string {
return origLogger.Level.String()
}
// Set implements flag.Value.
func (f levelFlag) Set(level string) error {
l, err := logrus.ParseLevel(level)
if err != nil {
return err
}
origLogger.Level = l
return nil
}
// setSyslogFormatter is nil if the target architecture does not support syslog.
var setSyslogFormatter func(string, string) error
func setJSONFormatter() {
origLogger.Formatter = &logrus.JSONFormatter{}
}
type logFormatFlag struct{ uri string }
// String implements flag.Value.
func (f logFormatFlag) String() string {
return f.uri
}
// Set implements flag.Value.
func (f logFormatFlag) Set(format string) error {
f.uri = format
u, err := url.Parse(format)
if err != nil {
return err
}
if u.Scheme != "logger" {
return fmt.Errorf("invalid scheme %s", u.Scheme)
}
jsonq := u.Query().Get("json")
if jsonq == "true" {
setJSONFormatter()
}
switch u.Opaque {
case "syslog":
if setSyslogFormatter == nil {
return fmt.Errorf("system does not support syslog")
}
appname := u.Query().Get("appname")
facility := u.Query().Get("local")
return setSyslogFormatter(appname, facility)
case "stdout":
origLogger.Out = os.Stdout
case "stderr":
origLogger.Out = os.Stderr
default:
return fmt.Errorf("unsupported logger %s", u.Opaque)
}
return nil
}
func init() {
AddFlags(flag.CommandLine)
}
// AddFlags adds the flags used by this package to the given FlagSet. That's
// useful if working with a custom FlagSet. The init function of this package
// adds the flags to flag.CommandLine anyway. Thus, it's usually enough to call
// flag.Parse() to make the logging flags take effect.
func AddFlags(fs *flag.FlagSet) {
fs.Var(levelFlag{}, "log.level", "Only log messages with the given severity or above. Valid levels: [debug, info, warn, error, fatal].")
fs.Var(logFormatFlag{}, "log.format", "If set use a syslog logger or JSON logging. Example: logger:syslog?appname=bob&local=7 or logger:stdout?json=true. Defaults to stderr.")
}
type Logger interface {
Debug(...interface{})
Debugln(...interface{})
Debugf(string, ...interface{})
Info(...interface{})
Infoln(...interface{})
Infof(string, ...interface{})
Warn(...interface{})
Warnln(...interface{})
Warnf(string, ...interface{})
Error(...interface{})
Errorln(...interface{})
Errorf(string, ...interface{})
Fatal(...interface{})
Fatalln(...interface{})
Fatalf(string, ...interface{})
With(key string, value interface{}) Logger
}
type logger struct {
entry *logrus.Entry
}
func (l logger) With(key string, value interface{}) Logger {
return logger{l.entry.WithField(key, value)}
}
// Debug logs a message at level Debug on the standard logger.
func (l logger) Debug(args ...interface{}) {
l.sourced().Debug(args...)
}
// Debug logs a message at level Debug on the standard logger.
func (l logger) Debugln(args ...interface{}) {
l.sourced().Debugln(args...)
}
// Debugf logs a message at level Debug on the standard logger.
func (l logger) Debugf(format string, args ...interface{}) {
l.sourced().Debugf(format, args...)
}
// Info logs a message at level Info on the standard logger.
func (l logger) Info(args ...interface{}) {
l.sourced().Info(args...)
}
// Info logs a message at level Info on the standard logger.
func (l logger) Infoln(args ...interface{}) {
l.sourced().Infoln(args...)
}
// Infof logs a message at level Info on the standard logger.
func (l logger) Infof(format string, args ...interface{}) {
l.sourced().Infof(format, args...)
}
// Warn logs a message at level Warn on the standard logger.
func (l logger) Warn(args ...interface{}) {
l.sourced().Warn(args...)
}
// Warn logs a message at level Warn on the standard logger.
func (l logger) Warnln(args ...interface{}) {
l.sourced().Warnln(args...)
}
// Warnf logs a message at level Warn on the standard logger.
func (l logger) Warnf(format string, args ...interface{}) {
l.sourced().Warnf(format, args...)
}
// Error logs a message at level Error on the standard logger.
func (l logger) Error(args ...interface{}) {
l.sourced().Error(args...)
}
// Error logs a message at level Error on the standard logger.
func (l logger) Errorln(args ...interface{}) {
l.sourced().Errorln(args...)
}
// Errorf logs a message at level Error on the standard logger.
func (l logger) Errorf(format string, args ...interface{}) {
l.sourced().Errorf(format, args...)
}
// Fatal logs a message at level Fatal on the standard logger.
func (l logger) Fatal(args ...interface{}) {
l.sourced().Fatal(args...)
}
// Fatal logs a message at level Fatal on the standard logger.
func (l logger) Fatalln(args ...interface{}) {
l.sourced().Fatalln(args...)
}
// Fatalf logs a message at level Fatal on the standard logger.
func (l logger) Fatalf(format string, args ...interface{}) {
l.sourced().Fatalf(format, args...)
}
// sourced adds a source field to the logger that contains
// the file name and line where the logging happened.
func (l logger) sourced() *logrus.Entry {
_, file, line, ok := runtime.Caller(2)
if !ok {
file = "<???>"
line = 1
} else {
slash := strings.LastIndex(file, "/")
file = file[slash+1:]
}
return l.entry.WithField("source", fmt.Sprintf("%s:%d", file, line))
}
var origLogger = logrus.New()
var baseLogger = logger{entry: logrus.NewEntry(origLogger)}
func Base() Logger {
return baseLogger
}
func With(key string, value interface{}) Logger {
return baseLogger.With(key, value)
}
// Debug logs a message at level Debug on the standard logger.
func Debug(args ...interface{}) {
baseLogger.sourced().Debug(args...)
}
// Debug logs a message at level Debug on the standard logger.
func Debugln(args ...interface{}) {
baseLogger.sourced().Debugln(args...)
}
// Debugf logs a message at level Debug on the standard logger.
func Debugf(format string, args ...interface{}) {
baseLogger.sourced().Debugf(format, args...)
}
// Info logs a message at level Info on the standard logger.
func Info(args ...interface{}) {
baseLogger.sourced().Info(args...)
}
// Info logs a message at level Info on the standard logger.
func Infoln(args ...interface{}) {
baseLogger.sourced().Infoln(args...)
}
// Infof logs a message at level Info on the standard logger.
func Infof(format string, args ...interface{}) {
baseLogger.sourced().Infof(format, args...)
}
// Warn logs a message at level Warn on the standard logger.
func Warn(args ...interface{}) {
baseLogger.sourced().Warn(args...)
}
// Warn logs a message at level Warn on the standard logger.
func Warnln(args ...interface{}) {
baseLogger.sourced().Warnln(args...)
}
// Warnf logs a message at level Warn on the standard logger.
func Warnf(format string, args ...interface{}) {
baseLogger.sourced().Warnf(format, args...)
}
// Error logs a message at level Error on the standard logger.
func Error(args ...interface{}) {
baseLogger.sourced().Error(args...)
}
// Error logs a message at level Error on the standard logger.
func Errorln(args ...interface{}) {
baseLogger.sourced().Errorln(args...)
}
// Errorf logs a message at level Error on the standard logger.
func Errorf(format string, args ...interface{}) {
baseLogger.sourced().Errorf(format, args...)
}
// Fatal logs a message at level Fatal on the standard logger.
func Fatal(args ...interface{}) {
baseLogger.sourced().Fatal(args...)
}
// Fatal logs a message at level Fatal on the standard logger.
func Fatalln(args ...interface{}) {
baseLogger.sourced().Fatalln(args...)
}
// Fatalf logs a message at level Fatal on the standard logger.
func Fatalf(format string, args ...interface{}) {
baseLogger.sourced().Fatalf(format, args...)
}
type errorLogWriter struct{}
func (errorLogWriter) Write(b []byte) (int, error) {
baseLogger.sourced().Error(string(b))
return len(b), nil
}
// NewErrorLogger returns a log.Logger that is meant to be used
// in the ErrorLog field of an http.Server to log HTTP server errors.
func NewErrorLogger() *log.Logger {
return log.New(&errorLogWriter{}, "", 0)
}

View File

@ -0,0 +1,119 @@
// Copyright 2015 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build !windows,!nacl,!plan9
package log
import (
"fmt"
"log/syslog"
"os"
"github.com/Sirupsen/logrus"
)
func init() {
setSyslogFormatter = func(appname, local string) error {
if appname == "" {
return fmt.Errorf("missing appname parameter")
}
if local == "" {
return fmt.Errorf("missing local parameter")
}
fmter, err := newSyslogger(appname, local, origLogger.Formatter)
if err != nil {
fmt.Fprintf(os.Stderr, "error creating syslog formatter: %v\n", err)
origLogger.Errorf("can't connect logger to syslog: %v", err)
return err
}
origLogger.Formatter = fmter
return nil
}
}
var ceeTag = []byte("@cee:")
type syslogger struct {
wrap logrus.Formatter
out *syslog.Writer
}
func newSyslogger(appname string, facility string, fmter logrus.Formatter) (*syslogger, error) {
priority, err := getFacility(facility)
if err != nil {
return nil, err
}
out, err := syslog.New(priority, appname)
return &syslogger{
out: out,
wrap: fmter,
}, err
}
func getFacility(facility string) (syslog.Priority, error) {
switch facility {
case "0":
return syslog.LOG_LOCAL0, nil
case "1":
return syslog.LOG_LOCAL1, nil
case "2":
return syslog.LOG_LOCAL2, nil
case "3":
return syslog.LOG_LOCAL3, nil
case "4":
return syslog.LOG_LOCAL4, nil
case "5":
return syslog.LOG_LOCAL5, nil
case "6":
return syslog.LOG_LOCAL6, nil
case "7":
return syslog.LOG_LOCAL7, nil
}
return syslog.LOG_LOCAL0, fmt.Errorf("invalid local(%s) for syslog", facility)
}
func (s *syslogger) Format(e *logrus.Entry) ([]byte, error) {
data, err := s.wrap.Format(e)
if err != nil {
fmt.Fprintf(os.Stderr, "syslogger: can't format entry: %v\n", err)
return data, err
}
// only append tag to data sent to syslog (line), not to what
// is returned
line := string(append(ceeTag, data...))
switch e.Level {
case logrus.PanicLevel:
err = s.out.Crit(line)
case logrus.FatalLevel:
err = s.out.Crit(line)
case logrus.ErrorLevel:
err = s.out.Err(line)
case logrus.WarnLevel:
err = s.out.Warning(line)
case logrus.InfoLevel:
err = s.out.Info(line)
case logrus.DebugLevel:
err = s.out.Debug(line)
default:
err = s.out.Notice(line)
}
if err != nil {
fmt.Fprintf(os.Stderr, "syslogger: can't send log to syslog: %v\n", err)
}
return data, err
}

View File

@ -1,11 +0,0 @@
The Prometheus project was started by Matt T. Proud (emeritus) and
Julius Volz in 2012.
Maintainers of this repository:
* Julius Volz <julius.volz@gmail.com>
The following individuals have contributed code to this repository
(listed in alphabetical order):
* Julius Volz <julius.volz@gmail.com>

View File

@ -1,18 +0,0 @@
# Contributing
Prometheus uses GitHub to manage reviews of pull requests.
* If you have a trivial fix or improvement, go ahead and create a pull
request, addressing (with `@...`) one or more of the maintainers
(see [AUTHORS.md](AUTHORS.md)) in the description of the pull request.
* If you plan to do something more involved, first discuss your ideas
on our [mailing list](https://groups.google.com/forum/?fromgroups#!forum/prometheus-developers).
This will avoid unnecessary work and surely give you and us a good deal
of inspiration.
* Relevant coding style guidelines are the [Go Code Review
Comments](https://code.google.com/p/go-wiki/wiki/CodeReviewComments)
and the _Formatting and style_ section of Peter Bourgon's [Go: Best
Practices for Production
Environments](http://peter.bourgon.org/go-in-production/#formatting-and-style).

View File

@ -1,2 +0,0 @@
Standard logging library for Go-based Prometheus components.
Copyright 2015 The Prometheus Authors

View File

@ -1,10 +0,0 @@
# Prometheus Logging Library
**Deprecated: This repository is superseded by [common/log](https://github.com/prometheus/common/tree/master/log).**
Standard logging library for Go-based Prometheus components.
This library wraps
[https://github.com/Sirupsen/logrus](https://github.com/Sirupsen/logrus) in
order to add line:file annotations to log lines, as well as to provide common
command-line flags for Prometheus components using it.

View File

@ -1,171 +0,0 @@
// Copyright 2015 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package log
import (
"flag"
"runtime"
"strings"
"github.com/Sirupsen/logrus"
)
var logger = logrus.New()
type levelFlag struct{}
// String implements flag.Value.
func (f levelFlag) String() string {
return logger.Level.String()
}
// Set implements flag.Value.
func (f levelFlag) Set(level string) error {
l, err := logrus.ParseLevel(level)
if err != nil {
return err
}
logger.Level = l
return nil
}
func init() {
// In order for this flag to take effect, the user of the package must call
// flag.Parse() before logging anything.
flag.Var(levelFlag{}, "log.level", "Only log messages with the given severity or above. Valid levels: [debug, info, warn, error, fatal, panic].")
}
// fileLineEntry returns a logrus.Entry with file and line annotations for the
// original user log statement (two stack frames up from this function).
func fileLineEntry() *logrus.Entry {
_, file, line, ok := runtime.Caller(2)
if !ok {
file = "<???>"
line = 1
} else {
slash := strings.LastIndex(file, "/")
if slash >= 0 {
file = file[slash+1:]
}
}
return logger.WithFields(logrus.Fields{
"file": file,
"line": line,
})
}
// Debug logs a message at level Debug on the standard logger.
func Debug(args ...interface{}) {
fileLineEntry().Debug(args...)
}
// Debugln logs a message at level Debug on the standard logger.
func Debugln(args ...interface{}) {
fileLineEntry().Debugln(args...)
}
// Debugf logs a message at level Debug on the standard logger.
func Debugf(format string, args ...interface{}) {
fileLineEntry().Debugf(format, args...)
}
// Info logs a message at level Info on the standard logger.
func Info(args ...interface{}) {
fileLineEntry().Info(args...)
}
// Infoln logs a message at level Info on the standard logger.
func Infoln(args ...interface{}) {
fileLineEntry().Infoln(args...)
}
// Infof logs a message at level Info on the standard logger.
func Infof(format string, args ...interface{}) {
fileLineEntry().Infof(format, args...)
}
// Print logs a message at level Info on the standard logger.
func Print(args ...interface{}) {
fileLineEntry().Info(args...)
}
// Println logs a message at level Info on the standard logger.
func Println(args ...interface{}) {
fileLineEntry().Infoln(args...)
}
// Printf logs a message at level Info on the standard logger.
func Printf(format string, args ...interface{}) {
fileLineEntry().Infof(format, args...)
}
// Warn logs a message at level Warn on the standard logger.
func Warn(args ...interface{}) {
fileLineEntry().Warn(args...)
}
// Warnln logs a message at level Warn on the standard logger.
func Warnln(args ...interface{}) {
fileLineEntry().Warnln(args...)
}
// Warnf logs a message at level Warn on the standard logger.
func Warnf(format string, args ...interface{}) {
fileLineEntry().Warnf(format, args...)
}
// Error logs a message at level Error on the standard logger.
func Error(args ...interface{}) {
fileLineEntry().Error(args...)
}
// Errorln logs a message at level Error on the standard logger.
func Errorln(args ...interface{}) {
fileLineEntry().Errorln(args...)
}
// Errorf logs a message at level Error on the standard logger.
func Errorf(format string, args ...interface{}) {
fileLineEntry().Errorf(format, args...)
}
// Fatal logs a message at level Fatal on the standard logger.
func Fatal(args ...interface{}) {
fileLineEntry().Fatal(args...)
}
// Fatalln logs a message at level Fatal on the standard logger.
func Fatalln(args ...interface{}) {
fileLineEntry().Fatalln(args...)
}
// Fatalf logs a message at level Fatal on the standard logger.
func Fatalf(format string, args ...interface{}) {
fileLineEntry().Fatalf(format, args...)
}
// Panic logs a message at level Panic on the standard logger.
func Panic(args ...interface{}) {
fileLineEntry().Panicln(args...)
}
// Panicln logs a message at level Panic on the standard logger.
func Panicln(args ...interface{}) {
fileLineEntry().Panicln(args...)
}
// Panicf logs a message at level Panic on the standard logger.
func Panicf(format string, args ...interface{}) {
fileLineEntry().Panicf(format, args...)
}

14
vendor/vendor.json vendored
View File

@ -52,20 +52,22 @@
"revision": "5cb53e5c863aca6e2b8ec958d16d9a93753ecea6",
"revisionTime": "2015-12-08T14:32:55+01:00"
},
{
"checksumSHA1": "fKMoxZehNhXbklRQy7lpFAVH0XY=",
"path": "github.com/prometheus/common/log",
"revision": "bc0a4460d0fc2693fcdebafafbf07c6d18913b97",
"revisionTime": "2016-07-26T17:19:51Z"
},
{
"path": "github.com/prometheus/common/model",
"revision": "5cb53e5c863aca6e2b8ec958d16d9a93753ecea6",
"revisionTime": "2015-12-08T14:32:55+01:00"
},
{
"path": "github.com/prometheus/log",
"revision": "9a3136781e1ff7bc42736ba4acb81339b1422551",
"revisionTime": "2015-10-26T02:24:52+01:00"
},
{
"path": "github.com/prometheus/procfs",
"revision": "406e5b7bfd8201a36e2bb5f7bdae0b03380c2ce8",
"revisionTime": "2015-10-29T15:50:50-04:00"
}
]
],
"rootPath": "github.com/wrouesnel/postgres_exporter"
}