Esempio n. 1
0
func pullCommand(c *cli.Context) {
	args := c.Args()
	if len(args) < 1 {
		log.Fatal("rocker pull <image>")
	}

	dockerClient, err := dockerclient.NewFromCli(c)
	if err != nil {
		log.Fatal(err)
	}

	cacheDir, err := util.MakeAbsolute(c.String("cache-dir"))
	if err != nil {
		log.Fatal(err)
	}

	options := build.DockerClientOptions{
		Client:                   dockerClient,
		Auth:                     initAuth(c),
		Log:                      log.StandardLogger(),
		S3storage:                s3.New(dockerClient, cacheDir),
		StdoutContainerFormatter: log.StandardLogger().Formatter,
		StderrContainerFormatter: log.StandardLogger().Formatter,
	}
	client := build.NewDockerClient(options)

	if err := client.PullImage(args[0]); err != nil {
		log.Fatal(err)
	}
}
Esempio n. 2
0
func main() {
	flag.Parse()
	// connect with the logging server
	if logger != "" && (amroot || debug) {
		// blocks until we can connect to the logger
		lh, err := logutils.NewLoggerHook(logger, hostname, app)
		if err != nil {
			log.WithFields(log.Fields{
				"file": logutils.File(),
			}).Fatalln("ERROR SETTING UP LOGGING SERVER:", err)
		}
		log.AddHook(lh)
	}
	//log.Println("IN FORKEXEC")
	////log.SetOutput(ioutil.Discard)
	////log.Println("Log Test")
	////fmt.Println("exiting logger block")
	//}
	// log.Println("IN FORK EXEC")
	// recombine the flags for exec to use
	args := []string{
		"-failures=" + strconv.Itoa(failures),
		"-rfail=" + strconv.Itoa(rFail),
		"-ffail=" + strconv.Itoa(fFail),
		"-hostname=" + hostname,
		"-config=" + configFile,
		"-logger=" + logger,
		"-app=" + app,
		"-pprof=" + pprofaddr,
		"-physaddr=" + physaddr,
		"-rootwait=" + strconv.Itoa(rootwait),
		"-debug=" + strconv.FormatBool(debug),
		"-rounds=" + strconv.Itoa(rounds),
		"-amroot=" + strconv.FormatBool(amroot),
		"-test_connect=" + strconv.FormatBool(testConnect),
		"-suite=" + suite,
	}
	cmd := exec.Command("./exec", args...)
	cmd.Stdout = log.StandardLogger().Writer()
	cmd.Stderr = log.StandardLogger().Writer()
	// log.Println("running command:", cmd)
	err := cmd.Run()
	if err != nil {
		log.Errorln("cmd run:", err)
	}

	// get CPU usage stats
	st := cmd.ProcessState.SystemTime()
	ut := cmd.ProcessState.UserTime()
	log.WithFields(log.Fields{
		"file":     logutils.File(),
		"type":     "forkexec",
		"systime":  st,
		"usertime": ut,
	}).Info("")

}
Esempio n. 3
0
func CmdImport(databaseName, filePath, mongoCollection, mongoDatabase string, id IDb, is services.IServices, ij jobs.IJobs) error {
	if _, err := os.Stat(filePath); os.IsNotExist(err) {
		return fmt.Errorf("A file does not exist at path '%s'", filePath)
	}
	service, err := is.RetrieveByLabel(databaseName)
	if err != nil {
		return err
	}
	if service == nil {
		return fmt.Errorf("Could not find a service with the label \"%s\". You can list services with the \"catalyze services\" command.", databaseName)
	}
	logrus.Printf("Backing up \"%s\" before performing the import", databaseName)
	job, err := id.Backup(service)
	if err != nil {
		return err
	}
	logrus.Printf("Backup started (job ID = %s)", job.ID)

	// all because logrus treats print, println, and printf the same
	logrus.StandardLogger().Out.Write([]byte("Polling until backup finishes."))
	status, err := ij.PollTillFinished(job.ID, service.ID)
	if err != nil {
		return err
	}
	job.Status = status
	logrus.Printf("\nEnded in status '%s'", job.Status)
	err = id.DumpLogs("backup", job, service)
	if err != nil {
		return err
	}
	if job.Status != "finished" {
		return fmt.Errorf("Job finished with invalid status %s", job.Status)
	}
	logrus.Printf("Importing '%s' into %s (ID = %s)", filePath, databaseName, service.ID)
	job, err = id.Import(filePath, mongoCollection, mongoDatabase, service)
	if err != nil {
		return err
	}
	// all because logrus treats print, println, and printf the same
	logrus.StandardLogger().Out.Write([]byte(fmt.Sprintf("Processing import (job ID = %s).", job.ID)))

	status, err = ij.PollTillFinished(job.ID, service.ID)
	if err != nil {
		return err
	}
	job.Status = status
	logrus.Printf("\nImport complete (end status = '%s')", job.Status)
	err = id.DumpLogs("restore", job, service)
	if err != nil {
		return err
	}
	if job.Status != "finished" {
		return fmt.Errorf("Finished with invalid status %s", job.Status)
	}
	return nil
}
Esempio n. 4
0
func init() {
	flag.Usage = func() {
		fmt.Fprint(os.Stderr, fmt.Sprintf(banner, version, os.Args[0]))
		flag.PrintDefaults()
	}

	flag.BoolVar(&movie, "movie", false, "parse as movie file")
	flag.BoolVar(&tv, "tv", false, "parse as TV file")
	flag.BoolVar(&showVersion, "showVersion", false, "show showVersion and exit")
	flag.StringVar(&format, "format", "", "output format")
	flag.Parse()
	filenames = flag.Args()

	// Set debug level
	if debug {
		log.StandardLogger().Level = log.DebugLevel
	} else {
		log.StandardLogger().Level = log.ErrorLevel
	}

	if movie && tv {
		fmt.Fprintln(os.Stderr, "Cannot use both -movie and -tv simultaneously")
		flag.Usage()
		os.Exit(1)
	}

	if !movie && !tv {
		fmt.Fprintln(os.Stderr, "Please provide -movie or -tv")
		flag.Usage()
		os.Exit(1)
	}

	if showVersion {
		fmt.Println(version)
		os.Exit(0)
	}

	if len(filenames) == 0 {
		fmt.Fprintln(os.Stderr, "No input provided")
		flag.Usage()
		os.Exit(1)
	}

	// Set default format if -format is omitted
	if strings.Trim(format, " ") == "" {
		if movie {
			format = "{{spaces .Title | title | underscores}}.{{.Year}}.{{.Ext}}"
		} else {
			format = `{{spaces .Title | title | underscores}}.{{printf "%02d" .Season}}{{printf "%02d" .Episode}}.{{.Ext}}`
		}
	}
}
Esempio n. 5
0
func (m *mod) Start() error {
	stdOut := log.StandardLogger().Writer()
	stdErr := log.StandardLogger().Writer()

	r := mux.NewRouter()

	r.Handle("/r/module/instances",
		handlers.LoggingHandler(stdOut, http.HandlerFunc(moduleInstHandler)))
	r.Handle("/r/module/instances/{id}/start",
		handlers.LoggingHandler(stdOut, http.HandlerFunc(moduleInstStartHandler)))
	r.Handle("/r/module/types",
		handlers.LoggingHandler(stdOut, http.HandlerFunc(moduleTypeHandler)))

	r.Handle("/images/rexray-banner-logo.svg",
		handlers.LoggingHandler(stdOut, http.HandlerFunc(imagesHandler)))
	r.Handle("/scripts/jquery-1.11.3.min.js",
		handlers.LoggingHandler(stdOut, http.HandlerFunc(scriptsHandler)))
	r.Handle("/styles/main.css",
		handlers.LoggingHandler(stdOut, http.HandlerFunc(stylesHandler)))

	r.Handle("/",
		handlers.LoggingHandler(stdOut, http.HandlerFunc(indexHandler)))

	_, addr, parseAddrErr := util.ParseAddress(m.Address())
	if parseAddrErr != nil {
		return parseAddrErr
	}

	s := &http.Server{
		Addr:           addr,
		Handler:        r,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
		ErrorLog:       golog.New(stdErr, "", 0),
	}

	go func() {
		defer stdOut.Close()
		defer stdErr.Close()

		sErr := s.ListenAndServe()
		if sErr != nil {
			panic(sErr)
		}
	}()

	return nil
}
Esempio n. 6
0
func TestLogrusWithJsonFormatter(t *testing.T) {
	p := &Person{
		Name:  "Bruce",
		Alias: "Batman",
		Hideout: &Hideout{
			Name:        "JLU Tower",
			DimensionId: 52,
		},
	}

	log.SetFormatter(newJsonFormatter())

	entry := log.NewEntry(log.StandardLogger())
	entry.Message = "the dark knight"
	entry.Data = log.Fields{"hero": p}
	s, _ := entry.String()

	if !strings.Contains(s, `"hero.name":"Bruce"`) {
		t.Fatalf(`missing "hero.name":"Bruce"`)
	}

	if !strings.Contains(s, `"hero.alias":"Batman"`) {
		t.Fatalf(`missing "hero.alias":"Batman"`)
	}

	if !strings.Contains(s, `"hero.hideout.name":"JLU Tower"`) {
		t.Fatalf(`missing "hero.hideout.name":"JLU Tower"`)
	}

	if !strings.Contains(s, `"hero.hideout.dimensionId":52`) {
		t.Fatalf(`missing "hero.hideout.dimensionId":52`)
	}
}
Esempio n. 7
0
// Validate validates the provided data (d) against the provided schema (s).
func Validate(ctx types.Context, s, d []byte) error {

	if ctx == nil {
		log.StandardLogger().WithFields(log.Fields{
			"schema": string(s),
			"body":   string(d),
		}).Debug("validating schema")
	} else {
		ctx.WithFields(log.Fields{
			"schema": string(s),
			"body":   string(d),
		}).Debug("validating schema")
	}

	validator, err := getSchemaValidator(s)
	if err != nil {
		return err
	}

	if len(d) == 0 {
		d = []byte("{}")
	}

	data, err := ucl.Parse(bytes.NewReader(d))
	if err != nil {
		return err
	}
	return validator.Validate(data)
}
Esempio n. 8
0
// NewFeedWatcher returns a new FeedWatcher instance.
func NewFeedWatcher(
	feedInfo db.FeedInfo,
	crawlChan chan *FeedCrawlRequest,
	responseChan chan *FeedCrawlResponse,
	mailChan chan *mail.Request,
	dbh db.Service,
	GUIDCache []string,
	minSleep int64,
	maxSleep int64,
) *FeedWatcher {
	guids := map[string]bool{}
	for _, i := range GUIDCache {
		guids[i] = true
	}
	return &FeedWatcher{
		FeedInfo:          feedInfo,
		exitChan:          make(chan int),
		crawlChan:         crawlChan,
		responseChan:      responseChan,
		mailerChan:        mailChan,
		polling:           false,
		crawling:          false,
		minSleepTime:      time.Duration(minSleep) * time.Second,
		maxSleepTime:      time.Duration(maxSleep) * time.Second,
		dbh:               dbh,
		GUIDCache:         guids,
		LastCrawlResponse: &FeedCrawlResponse{},
		After:             After,
		Logger:            logrus.StandardLogger(),
	}
}
Esempio n. 9
0
func CmdBackup(databaseName string, skipPoll bool, id IDb, is services.IServices, ij jobs.IJobs) error {
	service, err := is.RetrieveByLabel(databaseName)
	if err != nil {
		return err
	}
	if service == nil {
		return fmt.Errorf("Could not find a service with the label \"%s\". You can list services with the \"catalyze services\" command.", databaseName)
	}
	job, err := id.Backup(service)
	if err != nil {
		return err
	}
	logrus.Printf("Backup started (job ID = %s)", job.ID)
	if !skipPoll {
		// all because logrus treats print, println, and printf the same
		logrus.StandardLogger().Out.Write([]byte("Polling until backup finishes."))
		status, err := ij.PollTillFinished(job.ID, service.ID)
		if err != nil {
			return err
		}
		job.Status = status
		logrus.Printf("\nEnded in status '%s'", job.Status)
		err = id.DumpLogs("backup", job, service)
		if err != nil {
			return err
		}
		if job.Status != "finished" {
			return fmt.Errorf("Job finished with invalid status %s", job.Status)
		}
	}
	logrus.Printf("You can download your backup with the \"catalyze db download %s %s ./output_file_path\" command", databaseName, job.ID)
	return nil
}
Esempio n. 10
0
func configureSyslog(syslogParam string) {
	var err error
	var hook log.Hook

	// disable colors if we're writing to syslog *and* we're the default text
	// formatter, because the tty detection is useless here.
	if tf, ok := log.StandardLogger().Formatter.(*log.TextFormatter); ok {
		tf.DisableColors = true
	}

	if syslogParam == "kernel" {
		hook, err = logrus_syslog.NewSyslogHook("", "", syslog.LOG_INFO, "netplugin")
		if err != nil {
			log.Fatalf("Could not connect to kernel syslog")
		}
	} else {
		u, err := url.Parse(syslogParam)
		if err != nil {
			log.Fatalf("Could not parse syslog spec: %v", err)
		}

		hook, err = logrus_syslog.NewSyslogHook(u.Scheme, u.Host, syslog.LOG_INFO, "netplugin")
		if err != nil {
			log.Fatalf("Could not connect to syslog: %v", err)
		}
	}

	log.AddHook(hook)
}
Esempio n. 11
0
func CmdList(is ISites, iservices services.IServices) error {
	serviceProxy, err := iservices.RetrieveByLabel("service_proxy")
	if err != nil {
		return err
	}
	sites, err := is.List(serviceProxy.ID)
	if err != nil {
		return err
	}
	if sites == nil || len(*sites) == 0 {
		logrus.Println("No sites found")
		return nil
	}
	svcs, err := iservices.List()
	svcMap := map[string]string{}
	for _, s := range *svcs {
		svcMap[s.ID] = s.Label
	}

	data := [][]string{{"NAME", "CERT", "UPSTREAM SERVICE"}}
	for _, s := range *sites {
		data = append(data, []string{s.Name, s.Cert, svcMap[s.UpstreamService]})
	}

	table := tablewriter.NewWriter(logrus.StandardLogger().Out)
	table.SetBorder(false)
	table.SetRowLine(false)
	table.SetCenterSeparator("")
	table.SetColumnSeparator("")
	table.SetRowSeparator("")
	table.AppendBulk(data)
	table.Render()
	return nil
}
Esempio n. 12
0
func main() {
	envflag.Parse()

	if *debug {
		logrus.SetLevel(logrus.DebugLevel)
	} else {
		logrus.SetLevel(logrus.WarnLevel)
	}

	handler := router.Load(
		ginrus.Ginrus(logrus.StandardLogger(), time.RFC3339, true),
		middleware.Version,
		middleware.Store(),
		middleware.Remote(),
		middleware.Cache(),
	)

	if *cert != "" {
		logrus.Fatal(
			http.ListenAndServeTLS(*addr, *cert, *key, handler),
		)
	} else {
		logrus.Fatal(
			http.ListenAndServe(*addr, handler),
		)
	}
}
Esempio n. 13
0
func init() {
	// 初始化日志
	logrus.SetFormatter(&logrus.JSONFormatter{})
	log.SetOutput(logrus.StandardLogger().Out)

	// 初始化配置
	Config = loadConfig()
	lv, err := logrus.ParseLevel(Config.LogLevel)
	if err != nil {
		logrus.WithError(err).Warn("解析日志等级出错")
		lv = logrus.DebugLevel
	}
	logrus.SetLevel(lv)

	if Config.ReportOn {
		hook, err := logrus_mail.NewMailAuthHook(Config.AppName,
			Config.MailerHost,
			Config.MailerPort,
			Config.MailerUser,
			Config.MailReceiver,
			Config.MailerUser,
			Config.MailerPass)
		if err == nil {
			logrus.AddHook(hook)
		}
	}
	exeRoot := filepath.Dir(os.Args[0])
	f, err := os.OpenFile(filepath.Join(exeRoot, "retask.log"), os.O_APPEND|os.O_CREATE, os.ModePerm)
	if err != nil {
		logrus.WithError(err).Fatal("打开日志文件失败")
	}
	logrus.SetOutput(f)

}
func runServer(neoURL string, port string, cacheDuration string, env string) {

	if duration, durationErr := time.ParseDuration(cacheDuration); durationErr != nil {
		log.Fatalf("Failed to parse cache duration string, %v", durationErr)
	} else {
		organisations.CacheControlHeader = fmt.Sprintf("max-age=%s, public", strconv.FormatFloat(duration.Seconds(), 'f', 0, 64))
	}

	conf := neoutils.ConnectionConfig{
		BatchSize:     1024,
		Transactional: false,
		HTTPClient: &http.Client{
			Transport: &http.Transport{
				MaxIdleConnsPerHost: 100,
			},
			Timeout: 1 * time.Minute,
		},
		BackgroundConnect: true,
	}
	db, err := neoutils.Connect(neoURL, &conf)

	if err != nil {
		log.Fatalf("Error connecting to neo4j %s", err)
	}

	organisations.OrganisationDriver = organisations.NewCypherDriver(db, env)

	servicesRouter := mux.NewRouter()

	// Healthchecks and standards first
	servicesRouter.HandleFunc("/__health", v1a.Handler("PublicOrganisationsRead Healthchecks",
		"Checks for accessing neo4j", organisations.HealthCheck()))

	servicesRouter.HandleFunc("/__gtg", organisations.GoodToGo)

	// Then API specific ones:
	servicesRouter.HandleFunc("/organisations/{uuid}", organisations.GetOrganisation).Methods("GET")

	servicesRouter.HandleFunc("/organisations/{uuid}", organisations.MethodNotAllowedHandler)

	var monitoringRouter http.Handler = servicesRouter
	monitoringRouter = httphandlers.TransactionAwareRequestLoggingHandler(log.StandardLogger(), monitoringRouter)
	monitoringRouter = httphandlers.HTTPMetricsHandler(metrics.DefaultRegistry, monitoringRouter)

	// The following endpoints should not be monitored or logged (varnish calls one of these every second, depending on config)
	// The top one of these build info endpoints feels more correct, but the lower one matches what we have in Dropwizard,
	// so it's what apps expect currently same as ping, the content of build-info needs more definition
	//using http router here to be able to catch "/"
	http.HandleFunc(status.PingPath, status.PingHandler)
	http.HandleFunc(status.PingPathDW, status.PingHandler)
	http.HandleFunc(status.BuildInfoPath, status.BuildInfoHandler)
	http.HandleFunc(status.BuildInfoPathDW, status.BuildInfoHandler)
	http.HandleFunc("/__gtg", organisations.GoodToGo)
	http.Handle("/", monitoringRouter)

	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatalf("Unable to start server: %v", err)
	}

}
Esempio n. 15
0
func main() {
	flag.Parse()

	ch, err := tchannel.NewChannel("ping", nil)
	if err != nil {
		log.Fatalf("channel did not create successfully: %v", err)
	}

	logger := log.StandardLogger()

	worker := &worker{
		channel: ch,
		ringpop: ringpop.NewRingpop("ping-app", *hostport, ch, &ringpop.Options{
			Logger: bark.NewLoggerFromLogrus(logger),
		}),
		logger: logger,
	}

	if err := worker.RegisterPong(); err != nil {
		log.Fatalf("could not register pong handler: %v", err)
	}

	if err := worker.channel.ListenAndServe(*hostport); err != nil {
		log.Fatalf("could not listen on given hostport: %v", err)
	}

	opts := new(ringpop.BootstrapOptions)
	opts.File = *hostfile

	if _, err := worker.ringpop.Bootstrap(opts); err != nil {
		log.Fatalf("ringpop bootstrap failed: %v", err)
	}

	select {}
}
Esempio n. 16
0
// NewDockerClient makes a new client that works with a docker socket
func NewDockerClient(options DockerClientOptions) *DockerClient {
	log := options.Log
	if log == nil {
		log = logrus.StandardLogger()
	}

	u, err := url.Parse(options.Host)
	if err != nil {
		log.Errorf("Wrong host, can't parse: '%s'", options.Host)
	}

	isUnixSocket := ("unix" == u.Scheme)
	unixSockPath := u.Path

	return &DockerClient{
		client:                   options.Client,
		auth:                     options.Auth,
		log:                      log,
		s3storage:                options.S3storage,
		stdoutContainerFormatter: options.StdoutContainerFormatter,
		stderrContainerFormatter: options.StderrContainerFormatter,
		pushRetryCount:           options.PushRetryCount,
		isUnixSocket:             isUnixSocket,
		unixSockPath:             unixSockPath,
		useHumanSize:             !options.LogExactSizes,
	}
}
func RunServerWithConf(conf RWConf) {
	for path, service := range conf.Services {
		err := service.Initialise()
		if err != nil {
			log.Fatalf("Service for path %s could not startup, err=%s", path, err)
		}
	}

	if conf.Env != "local" {
		f, err := os.OpenFile("/var/log/apps/"+conf.ServiceName+"-go-app.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
		if err == nil {
			log.SetOutput(f)
			log.SetFormatter(&log.TextFormatter{DisableColors: true})
		} else {
			log.Fatalf("Failed to initialise log file, %v", err)
		}
		defer f.Close()
	}

	var m http.Handler
	m = router(conf.Services, conf.HealthHandler)
	if conf.EnableReqLog {
		m = httphandlers.TransactionAwareRequestLoggingHandler(log.StandardLogger(), m)
	}
	m = httphandlers.HTTPMetricsHandler(metrics.DefaultRegistry, m)

	http.Handle("/", m)

	log.Printf("listening on %d", conf.Port)
	log.Println(http.ListenAndServe(fmt.Sprintf(":%d", conf.Port), nil).Error())
	log.Printf("exiting on %s", conf.ServiceName)
}
Esempio n. 18
0
func NewLogrusLogger(ctx *cli.Context) Logger {
	logFile := ctx.GlobalString("log-file")
	if logFile != "" {
		if err := os.MkdirAll(path.Dir(logFile), 0755); err != nil {
			logrus.Errorf("Failed to create path %s: %s", path.Dir(logFile), err.Error())
		} else {
			file, err := os.OpenFile(logFile, syscall.O_CREAT|syscall.O_APPEND|syscall.O_WRONLY, 0644)
			if err != nil {
				logrus.Errorf("Failed to open log file %s: %s", logFile, err.Error())
			} else {
				logrus.SetOutput(file)
			}
		}
	}
	switch ctx.GlobalString("log-format") {
	case "json":
		logrus.SetFormatter(&logrus.JSONFormatter{})
	case "logstash":
		logrus.SetFormatter(&logstash.LogstashFormatter{})
	default:
		logrus.SetFormatter(&logrus.TextFormatter{})
	}
	if ctx.GlobalBool("debug") {
		logrus.SetLevel(logrus.DebugLevel)
	}

	return &logrusLogger{
		logger: logrus.StandardLogger(),
	}
}
Esempio n. 19
0
func CmdShow(name string, is ISites, iservices services.IServices) error {
	serviceProxy, err := iservices.RetrieveByLabel("service_proxy")
	if err != nil {
		return err
	}
	sites, err := is.List(serviceProxy.ID)
	if err != nil {
		return err
	}
	var site *models.Site
	for _, s := range *sites {
		if s.Name == name {
			site = &s
			break
		}
	}
	if site == nil {
		return fmt.Errorf("Could not find a site with the label \"%s\". You can list sites with the \"catalyze sites list\" command.", name)
	}
	site, err = is.Retrieve(site.ID, serviceProxy.ID)
	if err != nil {
		return err
	}
	table, err := simpletable.New(simpletable.HeadersForType(models.Site{}), []models.Site{*site})
	if err != nil {
		return err
	}
	table.Write(logrus.StandardLogger().Out)
	return nil
}
Esempio n. 20
0
func main() {
	flag.Usage = func() {
		fmt.Println("Usage: quilt " +
			"[-log-level=<level> | -l=<level>] [-H=<listen_address>] " +
			"[log-file=<log_output_file>] " +
			"[daemon | inspect <stitch> | run <stitch> | minion | " +
			"stop <namespace> | get <import_path> | " +
			"machines | containers | ssh <machine> | " +
			"exec <container> <command> | " +
			"logs <container>]")
		fmt.Println("\nWhen provided a stitch, quilt takes responsibility\n" +
			"for deploying it as specified.  Alternatively, quilt may be\n" +
			"instructed to stop all deployments in a given namespace,\n" +
			"or the default namespace if none is provided.\n")
		flag.PrintDefaults()
		fmt.Println("        Valid logger levels are:\n" +
			"            debug, info, warn, error, fatal or panic.")
	}

	var logOut = flag.String("log-file", "", "log output file (will be overwritten)")
	var logLevel = flag.String("log-level", "info", "level to set logger to")
	flag.StringVar(logLevel, "l", "info", "level to set logger to")
	flag.Parse()

	level, err := parseLogLevel(*logLevel)
	if err != nil {
		fmt.Println(err)
		usage()
	}
	log.SetLevel(level)
	log.SetFormatter(util.Formatter{})

	if *logOut != "" {
		file, err := os.Create(*logOut)
		if err != nil {
			fmt.Printf("Failed to create file %s\n", *logOut)
			os.Exit(1)
		}
		defer file.Close()
		log.SetOutput(file)
	}

	// GRPC spews a lot of useless log messages so we tell to eat its logs, unless
	// we are in debug mode
	grpclog.SetLogger(l_mod.New(ioutil.Discard, "", 0))
	if level == log.DebugLevel {
		grpclog.SetLogger(log.StandardLogger())
	}

	if len(flag.Args()) == 0 {
		usage()
	}

	subcommand := flag.Arg(0)
	if quiltctl.HasSubcommand(subcommand) {
		quiltctl.Run(subcommand, flag.Args()[1:])
	} else {
		usage()
	}
}
Esempio n. 21
0
// GetLogrusLogger returns the logrus logger for the context. If one more keys
// are provided, they will be resolved on the context and included in the
// logger. Only use this function if specific logrus functionality is
// required.
func getLogrusLogger(ctx Context, keys ...interface{}) *logrus.Entry {
	var logger *logrus.Entry

	// Get a logger, if it is present.
	loggerInterface := ctx.Value("logger")
	if loggerInterface != nil {
		if lgr, ok := loggerInterface.(*logrus.Entry); ok {
			logger = lgr
		}
	}

	if logger == nil {
		// If no logger is found, just return the standard logger.
		logger = logrus.NewEntry(logrus.StandardLogger())
	}

	fields := logrus.Fields{}

	for _, key := range keys {
		v := ctx.Value(key)
		if v != nil {
			fields[fmt.Sprint(key)] = v
		}
	}

	return logger.WithFields(fields)
}
Esempio n. 22
0
func main() {
	log := logrus.StandardLogger()

	configFileName := flag.String("c", "", "path to the configuration file")
	flag.Parse()

	if *configFileName == "" {
		log.Fatal("no configuration file specified")
	}

	configData, err := ioutil.ReadFile(*configFileName)
	if err != nil {
		log.Fatal("error reading configuration file: ", err.Error())
	}

	config, err := server.NewConfigFromYAML(configData)
	if err != nil {
		log.Fatal("error parsing configuration file: ", err.Error())
	}

	s, err := server.NewServer(log, config)
	if err != nil {
		log.Fatal(err.Error())
	}

	if err := s.ListenAndServe(); err != nil {
		log.Fatal(err.Error())
	}
}
Esempio n. 23
0
// we'll connect to the database through this function
func Init() {
	dbMutex.Lock()
	defer dbMutex.Unlock()

	if initialized {
		return
	}

	DBUrl = url.URL{
		Scheme:   "postgres",
		Host:     config.Constants.DbAddr,
		Path:     config.Constants.DbDatabase,
		RawQuery: "sslmode=disable",
	}

	logrus.Info("Connecting to DB on %s", DBUrl.String())

	DBUrl.User = url.UserPassword(config.Constants.DbUsername, config.Constants.DbPassword)

	var err error
	DB, err = gorm.Open("postgres", DBUrl.String())
	//	DB, err := gorm.Open("sqlite3", "/tmp/gorm.db")
	if err != nil {
		logrus.Fatal(err.Error())
	}

	DB.SetLogger(logrus.StandardLogger())

	logrus.Info("Connected!")
	initialized = true
}
Esempio n. 24
0
// Draw the square.
// Remember that the square should be ordered previously to make sure it
// prints in the intended order. Take a look at
// `github.com/Willyfrog/peano/matrix.Strategy` Interface
func (sq *Square) Draw(canvas *drawing.Canvas) {
	path := canvas.GetContext()
	if log.StandardLogger().Level == log.DebugLevel {
		if sq.X == 0 && sq.Y == 0 {
			path.SetStrokeColor(color.RGBA{0x44, 0xff, 0x44, 0xff})
		} else if sq.X == 0 && sq.Y == 1 {
			path.SetStrokeColor(color.RGBA{0xff, 0x44, 0x44, 0xff})
		} else {
			path.SetStrokeColor(color.RGBA{0xcc, 0xcc, 0xcc, 0xff})
		}
	} else {
		path.SetStrokeColor(color.RGBA{0xcc, 0xcc, 0xcc, 0xff})
	}

	path.SetLineWidth(1)
	xo, yo := sq.Origin()
	xe, ye := sq.End()
	drawing.DrawSquare(xo, yo, xe, ye, path)
	path.Stroke()
	//path.FillStroke()
	//log.Debug(fmt.Sprintf("Result: %v", sq.Points))
	var origin *point.Point
	for _, pt := range sq.Points {
		pt.Draw(canvas)
		if origin != nil {
			linepath := canvas.GetContext()
			path.SetStrokeColor(color.RGBA{0x44, 0x44, 0x88, 0xff})
			path.SetLineWidth(5)
			drawing.DrawLine(origin.X, origin.Y, pt.X, pt.Y, linepath)
			linepath.Stroke()
		}
		origin = pt
	}
}
Esempio n. 25
0
// GetLogrusLogger returns the logrus logger for the context. If one more keys
// are provided, they will be resolved on the context and included in the
// logger. Only use this function if specific logrus functionality is
// required.
func getLogrusLogger(ctx Context, keys ...interface{}) *logrus.Entry {
	var logger *logrus.Entry

	// Get a logger, if it is present.
	loggerInterface := ctx.Value("logger")
	if loggerInterface != nil {
		if lgr, ok := loggerInterface.(*logrus.Entry); ok {
			logger = lgr
		}
	}

	if logger == nil {
		fields := logrus.Fields{}

		// Fill in the instance id, if we have it.
		instanceID := ctx.Value("instance.id")
		if instanceID != nil {
			fields["instance.id"] = instanceID
		}

		fields["go.version"] = runtime.Version()
		// If no logger is found, just return the standard logger.
		logger = logrus.StandardLogger().WithFields(fields)
	}

	fields := logrus.Fields{}
	for _, key := range keys {
		v := ctx.Value(key)
		if v != nil {
			fields[fmt.Sprint(key)] = v
		}
	}

	return logger.WithFields(fields)
}
Esempio n. 26
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
	}
}
Esempio n. 27
0
func (d *driver) serfInit() error {
	var err error

	config := serf.DefaultConfig()
	config.Init()
	config.MemberlistConfig.BindAddr = d.bindAddress

	d.eventCh = make(chan serf.Event, 4)
	config.EventCh = d.eventCh
	config.UserCoalescePeriod = 1 * time.Second
	config.UserQuiescentPeriod = 50 * time.Millisecond

	config.LogOutput = logrus.StandardLogger().Out

	s, err := serf.Create(config)
	if err != nil {
		return fmt.Errorf("failed to create cluster node: %v", err)
	}
	defer func() {
		if err != nil {
			s.Shutdown()
		}
	}()

	d.serfInstance = s

	d.notifyCh = make(chan ovNotify)
	d.exitCh = make(chan chan struct{})

	go d.startSerfLoop(d.eventCh, d.notifyCh, d.exitCh)
	return nil
}
Esempio n. 28
0
// NewContainerFormatter returns an object that is given to logrus to better format
// contaienr output
func NewContainerFormatter(container *Container, level log.Level) log.Formatter {
	return &formatter{
		container: container,
		level:     level,
		delegate:  log.StandardLogger().Formatter,
	}
}
Esempio n. 29
0
func main() {
	r := gin.New()

	// Add a ginrus middleware, which:
	//   - Logs all requests, like a combined access and error log.
	//   - Logs to stdout.
	//   - RFC3339 with UTC time format.
	r.Use(ginrus.Ginrus(logrus.StandardLogger(), time.RFC3339, true))

	// Add similar middleware, but:
	//   - Only logs requests with errors, like an error log.
	//   - Logs to stderr instead of stdout.
	//   - Local time zone instead of UTC.
	logger := logrus.New()
	logger.Level = logrus.ErrorLevel
	logger.Out = os.Stderr
	r.Use(ginrus.Ginrus(logger, time.RFC3339, false))

	// Example ping request.
	r.GET("/ping", func(c *gin.Context) {
		c.String(200, "pong "+fmt.Sprint(time.Now().Unix()))
	})

	// Listen and Server in 0.0.0.0:8080
	r.Run(":8080")
}
Esempio n. 30
0
func (c *client) logResponse(res *http.Response) {

	if !c.logResponses {
		return
	}

	w := log.StandardLogger().Writer()

	fmt.Fprintln(w)
	fmt.Fprint(w, "    -------------------------- ")
	fmt.Fprint(w, "HTTP RESPONSE (CLIENT)")
	fmt.Fprintln(w, " -------------------------")

	buf, err := httputil.DumpResponse(
		res,
		res.Header.Get("Content-Type") != "application/octet-stream")
	if err != nil {
		return
	}

	bw := &bytes.Buffer{}
	gotil.WriteIndented(bw, buf)

	scanner := bufio.NewScanner(bw)
	for {
		if !scanner.Scan() {
			break
		}
		fmt.Fprintln(w, scanner.Text())
	}
}