• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang logrus.StandardLogger函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/Sirupsen/logrus.StandardLogger函数的典型用法代码示例。如果您正苦于以下问题:Golang StandardLogger函数的具体用法?Golang StandardLogger怎么用?Golang StandardLogger使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了StandardLogger函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: pullCommand

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)
	}
}
开发者ID:andrewrothstein,项目名称:rocker,代码行数:30,代码来源:main.go


示例2: main

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("")

}
开发者ID:ineiti,项目名称:prifi,代码行数:57,代码来源:forkexec.go


示例3: CmdImport

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
}
开发者ID:catalyzeio,项目名称:cli,代码行数:56,代码来源:import.go


示例4: init

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}}`
		}
	}
}
开发者ID:monstermunchkin,项目名称:goofy,代码行数:52,代码来源:main.go


示例5: Start

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
}
开发者ID:nutmegdevelopment,项目名称:rexray,代码行数:49,代码来源:admin.go


示例6: TestLogrusWithJsonFormatter

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`)
	}
}
开发者ID:akutz,项目名称:golf,代码行数:33,代码来源:json_formatter_test.go


示例7: Validate

// 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)
}
开发者ID:emccode,项目名称:libstorage,代码行数:30,代码来源:schema.go


示例8: NewFeedWatcher

// 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(),
	}
}
开发者ID:hobeone,项目名称:rss2go,代码行数:32,代码来源:feed_watcher.go


示例9: CmdBackup

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
}
开发者ID:catalyzeio,项目名称:cli,代码行数:33,代码来源:backup.go


示例10: configureSyslog

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)
}
开发者ID:karamsivia,项目名称:netplugin,代码行数:29,代码来源:netd.go


示例11: CmdList

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
}
开发者ID:catalyzeio,项目名称:cli,代码行数:34,代码来源:list.go


示例12: main

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),
		)
	}
}
开发者ID:jonbodner,项目名称:lgtm,代码行数:27,代码来源:main.go


示例13: init

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)

}
开发者ID:duanqy,项目名称:retask,代码行数:34,代码来源:main.go


示例14: runServer

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)
	}

}
开发者ID:Financial-Times,项目名称:public-organisations-api,代码行数:60,代码来源:app.go


示例15: main

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 {}
}
开发者ID:coderQQ,项目名称:ringpop-go,代码行数:35,代码来源:main.go


示例16: NewDockerClient

// 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,
	}
}
开发者ID:andrewrothstein,项目名称:rocker,代码行数:28,代码来源:client.go


示例17: RunServerWithConf

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)
}
开发者ID:Financial-Times,项目名称:base-ft-rw-app-go,代码行数:32,代码来源:baseftapp.go


示例18: NewLogrusLogger

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(),
	}
}
开发者ID:untoldwind,项目名称:eightyish,代码行数:30,代码来源:logger_logrus.go


示例19: CmdShow

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
}
开发者ID:catalyzeio,项目名称:cli,代码行数:30,代码来源:show.go


示例20: main

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()
	}
}
开发者ID:NetSys,项目名称:quilt,代码行数:60,代码来源:quilt.go



注:本文中的github.com/Sirupsen/logrus.StandardLogger函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang logrus.Warn函数代码示例发布时间:2022-05-28
下一篇:
Golang logrus.SetOutput函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap