Beispiel #1
0
func initLogs(ctx *cli.Context) {
	logger := log.StandardLogger()

	if ctx.GlobalBool("verbose") {
		logger.Level = log.DebugLevel
	}

	var (
		isTerm    = log.IsTerminal()
		json      = ctx.GlobalBool("json")
		useColors = isTerm && !json
	)

	if ctx.GlobalIsSet("colors") {
		useColors = ctx.GlobalBool("colors")
	}

	color.NoColor = !useColors

	if json {
		logger.Formatter = &log.JSONFormatter{}
	} else {
		formatter := &textformatter.TextFormatter{}
		formatter.DisableColors = !useColors

		logger.Formatter = formatter
	}
}
Beispiel #2
0
func (f *LogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
	b := &bytes.Buffer{}

	// Start by printing the time
	now := time.Now()
	fmt.Fprintf(b, "%s ", now.Format("2006-01-02 15:04:05"))

	// Upper case the log level
	levelText := strings.ToUpper(entry.Data["level"].(string))

	// Print the log level, but toggle the color
	if logrus.IsTerminal() {
		levelColor := green

		if entry.Data["level"] == "debug" {
			levelColor = blue
		} else if entry.Data["level"] == "warning" {
			levelColor = yellow
		} else if entry.Data["level"] == "error" || entry.Data["level"] == "fatal" || entry.Data["level"] == "panic" {
			levelColor = red
		}

		fmt.Fprintf(b, "\x1b[%dm[%-5s]\x1b[0m ", levelColor, levelText)
	} else {
		fmt.Fprintf(b, "[%-5s] ", levelText)
	}

	// Now print the message
	fmt.Fprintf(b, "%s ", entry.Data["msg"])

	// Print any extra data. By default, the data map has 3
	// elements.
	if len(entry.Data) > 3 {
		keys := make([]string, 0)
		for key, value := range entry.Data {
			if key != "time" && key != "level" && key != "msg" {
				if _, ok := value.(string); ok {
					keys = append(keys, fmt.Sprintf("%v: %s", key, value))
				} else {
					keys = append(keys, fmt.Sprintf("%v: %v", key, value))
				}
			}
		}

		fmt.Fprintf(b, "(%s)", strings.Join(keys, " "))
	}

	b.WriteByte('\n')

	return b.Bytes(), nil
}
Beispiel #3
0
func main() {

	flag.BoolVar(&debug, "debug", false, "")
	flag.StringVar(&pathToConfig, "c", "", "")

	flag.Usage = func() {

		fmt.Println(usage)

		os.Exit(0)
	}

	flag.Parse()

	if log.IsTerminal() {

		log.SetFormatter(&log.TextFormatter{
			FullTimestamp:   true,
			TimestampFormat: "2006-01-02 15:04:05 MST",
		})

	} else {

		log.SetFormatter(&log.JSONFormatter{
			TimestampFormat: "2006-01-02 15:04:05 MST",
		})
	}

	config, err := common.ReadConfig(pathToConfig)

	if err != nil {

		log.Fatalf("Error reading configuration file: %v", err)
	}

	if debug {
		log.SetLevel(log.DebugLevel)
	} else {
		log.SetLevel(config.LogLevel())
	}

	app := app.New(config)

	if debug {

		app.SetDebugMode()
	}

	app.Run()
}
Beispiel #4
0
func initLogs(ctx *cli.Context) {
	logger := log.StandardLogger()

	if ctx.GlobalBool("verbose") {
		logger.Level = log.DebugLevel
	} else if ctx.Bool("print") && ctx.GlobalString("log") == "" {
		logger.Level = log.ErrorLevel
	}

	var (
		err       error
		isTerm    = log.IsTerminal()
		logFile   = ctx.GlobalString("log")
		logExt    = path.Ext(logFile)
		json      = ctx.GlobalBool("json") || logExt == ".json"
		useColors = isTerm && !json && logFile == ""
	)

	if ctx.GlobalIsSet("colors") {
		useColors = ctx.GlobalBool("colors")
	}

	if logFile != "" {
		if logFile, err = toAbsolutePath(logFile, false); err != nil {
			log.Fatal(err)
		}
		if logger.Out, err = os.OpenFile(logFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644); err != nil {
			log.Fatalf("Initializing log: Cannot initialize log file %s due to error %s", logFile, err)
		}
		log.Debugf("Initializing log: Successfuly started loggin to '%s'", logFile)
	}

	if json {
		logger.Formatter = &log.JSONFormatter{}
	} else {
		formatter := &textformatter.TextFormatter{}
		formatter.DisableColors = !useColors
		logger.Formatter = formatter
	}
}
func init() {
	baseTimestamp = time.Now()
	isTerminal = logrus.IsTerminal()
}
Beispiel #6
0
func startDaemon() {

	var out io.Writer = os.Stdout
	if !log.IsTerminal() {
		logFile, logFileErr := util.LogFile("rexray.log")
		failOnError(logFileErr)
		out = io.MultiWriter(os.Stdout, logFile)
	}
	log.SetOutput(out)

	fmt.Fprintf(out, "%s\n", rexRayLogoASCII)
	util.PrintVersion(out)
	fmt.Fprintln(out)

	var success []byte
	var failure []byte
	var conn net.Conn

	if !fg {

		success = []byte{0}
		failure = []byte{1}

		var dialErr error

		log.Printf("dialing %s", client)
		conn, dialErr = net.Dial("unix", client)
		if dialErr != nil {
			panic(dialErr)
		}
	}

	writePidErr := util.WritePidFile(-1)
	if writePidErr != nil {
		if conn != nil {
			conn.Write(failure)
		}
		panic(writePidErr)
	}

	defer func() {
		r := recover()
		os.Remove(util.PidFilePath())
		if r != nil {
			panic(r)
		}
	}()

	log.Printf("created pid file, pid=%d", os.Getpid())

	init := make(chan error)
	sigc := make(chan os.Signal, 1)
	stop := make(chan os.Signal)

	signal.Notify(sigc,
		syscall.SIGKILL,
		syscall.SIGHUP,
		syscall.SIGINT,
		syscall.SIGTERM,
		syscall.SIGQUIT)

	go func() {
		rrdaemon.Start(r.Config.Host, init, stop)
	}()

	var initErrors []error

	for initErr := range init {
		initErrors = append(initErrors, initErr)
		log.Println(initErr)
	}

	if conn != nil {
		if len(initErrors) == 0 {
			conn.Write(success)
		} else {
			conn.Write(failure)
		}

		conn.Close()
	}

	if len(initErrors) > 0 {
		return
	}

	sigv := <-sigc
	log.Printf("received shutdown signal %v", sigv)
	stop <- sigv
}
Beispiel #7
0
func init() {
	isTerminal = logrus.IsTerminal()
}
Beispiel #8
0
func IsTerminal() bool {
	return logrus.IsTerminal()
}
 */

package build

import (
	"bytes"
	"fmt"
	log "github.com/Sirupsen/logrus"
	"runtime"
)

type containerFormatter struct {
	isColored bool
}

var isTerminal = log.IsTerminal()

// NewColoredContainerFormatter Returns Formatter that makes your messages outputed without any log-related data.
// Also, this formatter will make all messages colored (RED for now).
// Usefull when you want all stderr messages from container to become more noticible
func NewColoredContainerFormatter() log.Formatter {
	return &containerFormatter{
		isColored: true,
	}
}

// NewMonochromeContainerFormatter Returns Formatter that makes your messages outputed without any log-related data.
func NewMonochromeContainerFormatter() log.Formatter {
	return &containerFormatter{
		isColored: false,
	}
Beispiel #10
0
func isTerminal() bool {
	return log.IsTerminal()
}
Beispiel #11
0
package log

import (
	"bytes"
	"fmt"
	"runtime"
	"time"

	"github.com/Sirupsen/logrus"
	"github.com/mgutz/ansi"
)

var isTerminal = logrus.IsTerminal()

// PrettyFormatter is a formatter that meets the logrus.Formatter interface
type PrettyFormatter struct{}

// Format formats a logrus.Entry into an array of bytes
func (f *PrettyFormatter) Format(entry *logrus.Entry) ([]byte, error) {
	b := &bytes.Buffer{}
	isColored := isTerminal && (runtime.GOOS != "windows")
	if isColored {
		printColored(b, entry)
	} else {
		printUncolored(b, entry)
	}
	b.WriteByte('\n')
	return b.Bytes(), nil
}

func getLevelString(level logrus.Level) string {