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

Golang logrus.ParseLevel函数代码示例

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

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



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

示例1: InitializeLogging

func InitializeLogging(config *LoggingConfig, useStd bool, level string) {
	var lvl = log.DebugLevel
	var e error
	if level != "" {
		lvl, e = log.ParseLevel(level)
	} else if config.Level != "" {
		lvl, e = log.ParseLevel(config.Level)
	}
	if nil != e {
		lvl = log.DebugLevel
	}
	if useStd {
		log.SetOutput(os.Stdout)
		OUTPUT_FILE = nil
	} else {
		f, e := os.OpenFile(config.Filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
		if nil != e {
			fmt.Errorf("Open file <%s> for logging failed<%v>!\n", config.Filename, e)
		} else {
			log.SetOutput(f)
			OUTPUT_FILE = f
		}
	}
	if strings.ToLower(config.Format) == "json" {
		log.SetFormatter(&log.JSONFormatter{})
	} else {
		log.SetFormatter(&PlainFormatter{})
	}
	log.SetLevel(lvl)
	//log.Info("Logging Initialized.")
}
开发者ID:archsh,项目名称:hls-utils,代码行数:31,代码来源:logging.go


示例2: init

func init() {
	// ORDER MATTERs

	// configuration
	initConfig()

	// logging
	l := must(logrus.ParseLevel(config.Log.Level)).(logrus.Level)
	logrus.SetLevel(l)
	logrus.SetOutput(os.Stdout)

	// logging hooks
	graylogHookLevelThreshold := must(logrus.ParseLevel(config.Log.Graylog.Level)).(logrus.Level)
	graylogHook := must(
		grayloghook.New(
			config.Log.Graylog.Address,
			config.Log.Graylog.Facility,
			map[string]interface{}{
				"go_version": goVersion,
				"build_time": buildTime,
				"git_commit": gitCommit,
			},
			graylogHookLevelThreshold,
		),
	).(logrus.Hook)
	logrus.AddHook(graylogHook)

	// connection hub
	connsHub = list.New()

	// storage
	s := mysql.New(config.DB.DataSourceName)
	s.SetMaxOpenConns(config.DB.MaxOpenConns)
	s.SetMaxIdleConns(config.DB.MaxIdleConns)
	store = s

	// cache
	memoryCache = memory.New(config.Cache.NumCachedIncomes)
	total := must(store.GetLatestTotalReward()).(models.TotalReward)
	memoryCache.IncrementTotalReward(total.CreatedAt, total.Total)
	updateCache()

	// coin client
	initCoinClient(config.Coin.Type)

	// cronjob
	initCronjob(config.Coin.Type, config.CronjobSpec.CreateWithdrawal, config.CronjobSpec.ProcessWithdrawal)

	// mailer
	mailer = mandrill.New(config.Mandrill.Key, config.Mandrill.FromEmail, config.Mandrill.FromName)

	// geetest
	geetest = gt.New(config.Geetest.CaptchaID, config.Geetest.PrivateKey, false, time.Second*10, time.Second*10, 2048)

	// geo
	geo = must(geoip2.Open(config.Geo.Database)).(*geoip2.Reader)
}
开发者ID:solefaucet,项目名称:sole-server,代码行数:57,代码来源:main.go


示例3: init

func init() {
	conf := config.GetConfig()
	if conf == nil {
		conf = &config.Config{}
	}
	// Output to stderr instead of stdout, could also be a file.
	var output io.Writer
	switch conf.Log.Output.Path {
	case "stderr":
		output = os.Stderr
	case "stdout":
		output = os.Stdout
	default:
		logrus.Warn("No log output defined, using stderr")
		output = os.Stderr
	}
	log.Out = output

	// Only log the warning severity or above.
	level, err := logrus.ParseLevel(conf.Log.Output.Level)
	if err != nil {
		logrus.Warn("Cannot parse conf level, default to INFO")
	} else {
		log.Level = level
	}
	for _, hook := range conf.Log.Hook {
		switch hook.Type {
		case "syslog":
			priority := syslog.LOG_INFO
			if err != nil {
				logrus.Errorf("%v is not a valid priority, defaulting to Info", hook.Level)
			}
			h, err := logrus_syslog.NewSyslogHook(hook.Protocol, hook.URL, priority, "")
			if err != nil {
				logrus.Errorf("Unable to connect to syslog daemon %v:%v", hook.Protocol, hook.URL)
			} else {
				log.Hooks.Add(h)
			}
		case "logstash":
			level, err := logrus.ParseLevel(hook.Level)
			if err != nil {
				logrus.Warn("Cannot parse conf level, default to INFO")
			} else {
				log.Level = level
			}
			h, err := logstash_hook.NewLogstashHook(hook.Protocol, hook.URL, "application", level)
			if err != nil {
				logrus.Errorf("Unable to connect to logstash at %v:%v", hook.Protocol, hook.URL)

			} else {
				log.Hooks.Add(h)
			}
		}
	}
}
开发者ID:owulveryck,项目名称:gorchestrator,代码行数:55,代码来源:logger.go


示例4: main

// This is a minimal commandline client to connect through a websocket
func main() {
	kingpin.Parse()

	// set log level
	level, err := log.ParseLevel(*logLevel)
	if err != nil {
		logger.WithField("error", err).Fatal("Invalid log level")
	}
	log.SetLevel(level)

	origin := "http://localhost/"
	url := fmt.Sprintf("%v/user/%v", removeTrailingSlash(*url), *user)
	client, err := client.Open(url, origin, 100, true)
	if err != nil {
		log.Fatal(err)
	}

	go writeLoop(client)
	go readLoop(client)

	for _, cmd := range *commands {
		client.WriteRawMessage([]byte(cmd))
	}
	if *exit {
		return
	}
	waitForTermination(func() {})
}
开发者ID:smancke,项目名称:guble,代码行数:29,代码来源:main.go


示例5: NewLogger

// NewLogger returns a log configured with the input parameters.
func NewLogger(level, writer string, maxSize, maxAge, maxBackups int) *logrus.Entry {
	base := logrus.New()

	switch writer {
	case "stdout":
		base.Out = os.Stdout
	case "stderr":
		base.Out = os.Stderr
	case "":
		base.Out = ioutil.Discard
	default:
		base.Out = &lumberjack.Logger{
			Filename:   writer,
			MaxSize:    maxSize,
			MaxAge:     maxAge,
			MaxBackups: maxBackups,
		}
	}

	logrusLevel, err := logrus.ParseLevel(level)
	// if provided level is not supported, default to Info level
	if err != nil {
		base.Error(err)
		logrusLevel = logrus.InfoLevel
	}
	base.Level = logrusLevel

	log := logrus.NewEntry(base)
	return log
}
开发者ID:clawio,项目名称:clawiod,代码行数:31,代码来源:helpers.go


示例6: before

func before(c *cli.Context) error {
	initLogFormatter()
	initHelpAndVersionFlags()
	initAppHelpTemplate()

	// Log level
	if logLevel, err := log.ParseLevel(c.String(LogLevelKey)); err != nil {
		log.Fatal("[BITRISE_CLI] - Failed to parse log level:", err)
	} else {
		log.SetLevel(logLevel)
	}

	// Befor parsing cli, and running command
	// we need to decide wich path will be used by envman
	envman.CurrentEnvStoreFilePath = c.String(PathKey)
	if envman.CurrentEnvStoreFilePath == "" {
		if path, err := envStorePathInCurrentDir(); err != nil {
			log.Fatal("[ENVMAN] - Failed to set envman work path in current dir:", err)
		} else {
			envman.CurrentEnvStoreFilePath = path
		}
	}

	envman.ToolMode = c.Bool(ToolKey)
	if envman.ToolMode {
		log.Info("[ENVMAN] - Tool mode on")
	}

	if _, err := envman.GetConfigs(); err != nil {
		log.Fatal("[ENVMAN] - Failed to init configs:", err)
	}

	return nil
}
开发者ID:fbernardo,项目名称:envman,代码行数:34,代码来源:cli.go


示例7: initLogger

func initLogger() error {
	dirPath, _ := filepath.Abs(filepath.Dir(pConfig.Log.Path))
	if _, err := os.Stat(dirPath); os.IsNotExist(err) {
		os.Mkdir(dirPath, 0775)
	}

	file, err := os.OpenFile(pConfig.Log.Path, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)

	if err != nil {
		return err
	}

	level, err := logrus.ParseLevel(pConfig.Log.Level)
	if err != nil {
		return err
	}

	pLog = &logrus.Logger{
		Out:       file,
		Level:     level,
		Formatter: new(logrus.JSONFormatter),
	}

	pLog.Infof("InitLogger: path: %s, level: %s, formatter: json", pConfig.Log.Path, level)

	return nil
}
开发者ID:zheng-ji,项目名称:goTcpProxy,代码行数:27,代码来源:log.go


示例8: Execute

func Execute() {
	config.GetConfig().Load()
	checkFleetVersion()

	var logLevel string
	var rootCmd = &cobra.Command{
		Use: "green-garden",
		PersistentPreRun: func(cmd *cobra.Command, args []string) {
			level, err := log.ParseLevel(logLevel)
			if err != nil {
				fmt.Printf("Unknown log level : %s\n", logLevel)
				os.Exit(1)
			}
			log.SetLevel(level)
		},
	}
	rootCmd.PersistentFlags().StringVarP(&logLevel, "loglevel", "L", "info", "Set log level")
	rootCmd.AddCommand(versionCmd, generateCmd)

	loadEnvCommands(rootCmd)

	err := rootCmd.Execute()
	if err != nil {
		os.Exit(1)
	}
	log.Info("Victory !")
}
开发者ID:puckel,项目名称:green-garden,代码行数:27,代码来源:gg.go


示例9: SetLogLevel

func SetLogLevel(levelname string) {
	level, err := logrus.ParseLevel(levelname)
	if err != nil {
		Log.Fatal(err)
	}
	Log.Level = level
}
开发者ID:kidaa,项目名称:weave,代码行数:7,代码来源:logging.go


示例10: getAndValidateConfig

func (a *appConfig) getAndValidateConfig(cmd *cobra.Command) error {
	var err error

	a.port = viper.GetString("port")
	a.debug = viper.GetBool("debug")
	a.cpu = viper.GetInt("cpu")
	a.allowDegradedMode = viper.GetBool("allow-degraded-mode")

	// check logLevel values and set initLogLevel
	a.logLevel = viper.GetString("log-level")
	a.initLogLevel, err = log.ParseLevel(a.logLevel)
	if err != nil {
		err = fmt.Errorf("Invalid log level: \"%s\"\n%s", a.logLevel, cmd.Flags().Lookup("log-level").Usage)
		return err
	}

	// check db name
	a.db = viper.GetString("db")
	if a.db == "" {
		err = fmt.Errorf("Db name can't be empty\n%s", cmd.Flags().Lookup("db").Usage)
		return err
	}

	// Kafka brokers
	a.kafkaBrokerList = strings.Split(viper.GetString("kafka-brokers"), ",")
	if len(a.kafkaBrokerList) == 0 {
		err = fmt.Errorf("Broker list is empty or invalid format (%s)\n%s", a.kafkaBrokers, cmd.Flags().Lookup("kafka-brokers").Usage)
		return err
	}

	return nil
}
开发者ID:wojtekzw,项目名称:event-shuttle,代码行数:32,代码来源:event-shuttle.go


示例11: SetLevel

// SetLevel sets the log level. Valid levels are panic, fatal, error, warn, info and debug.
func SetLevel(level string) {
	lvl, err := log.ParseLevel(level)
	if err != nil {
		Fatal(fmt.Sprintf(`not a valid level: "%s"`, level))
	}
	log.SetLevel(lvl)
}
开发者ID:ninefive,项目名称:confd,代码行数:8,代码来源:log.go


示例12: 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


示例13: Configure

func Configure(loglevel string) {
	if level, err := logrus.ParseLevel(loglevel); err != nil {
		Logger.Fatal(err)
	} else {
		Logger.Level = level
	}
}
开发者ID:pombredanne,项目名称:octostats,代码行数:7,代码来源:log.go


示例14: enableFileLogger

func enableFileLogger() {
	flogger := serverConfig.GetFileLogger()
	if !flogger.Enable || flogger.Filename == "" {
		return
	}

	// Creates the named file with mode 0666, honors system umask.
	file, err := os.OpenFile(flogger.Filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
	fatalIf(err, "Unable to open log file.")

	fileLogger := logrus.New()

	// Add a local file hook.
	fileLogger.Hooks.Add(&localFile{file})

	lvl, err := logrus.ParseLevel(flogger.Level)
	fatalIf(err, "Unknown log level found in the config file.")

	// Set default JSON formatter.
	fileLogger.Out = ioutil.Discard
	fileLogger.Formatter = new(logrus.JSONFormatter)
	fileLogger.Level = lvl // Minimum log level.

	log.mu.Lock()
	log.loggers = append(log.loggers, fileLogger)
	log.mu.Unlock()
}
开发者ID:krishnasrinivas,项目名称:minio,代码行数:27,代码来源:logger-file-hook.go


示例15: setLogLevel

func (config *Config) setLogLevel() {
	level, err := log.ParseLevel(config.LogLevel)
	if err != nil {
		log.WithField("level", config.LogLevel).Fatal("bad level")
	}
	log.SetLevel(level)
}
开发者ID:sadhopedream,项目名称:marathon-consul,代码行数:7,代码来源:config.go


示例16: NewSlackHook

func NewSlackHook(options logrus_mate.Options) (hook logrus.Hook, err error) {
	conf := SlackHookConfig{}

	if err = options.ToObject(&conf); err != nil {
		return
	}

	levels := []logrus.Level{}

	if conf.Levels != nil {
		for _, level := range conf.Levels {
			if lv, e := logrus.ParseLevel(level); e != nil {
				err = e
				return
			} else {
				levels = append(levels, lv)
			}
		}
	}

	if len(levels) == 0 && conf.Levels != nil {
		levels = append(levels, logrus.ErrorLevel, logrus.PanicLevel, logrus.FatalLevel)
	}

	hook = &slackrus.SlackrusHook{
		HookURL:        conf.URL,
		AcceptedLevels: levels,
		Channel:        conf.Channel,
		IconEmoji:      conf.Emoji,
		Username:       conf.Username,
	}

	return
}
开发者ID:gogap,项目名称:logrus_mate,代码行数:34,代码来源:slack_hook.go


示例17: main

func main() {
	app := cli.NewApp()
	app.Name = path.Base(os.Args[0])
	app.Usage = "An entropy and failure injection management API for Docker platforms."
	app.Version = VERSION
	app.Authors = []cli.Author{{Name: "Jeff Nickoloff", Email: "[email protected]"}}
	app.Flags = flags
	app.Commands = commands
	app.Before = func(c *cli.Context) error {
		log.SetOutput(os.Stderr)
		level, err := log.ParseLevel(c.String("log-level"))
		if err != nil {
			log.Fatalf(err.Error())
		}
		log.SetLevel(level)

		// If a log level wasn't specified and we are running in debug mode,
		// enforce log-level=debug.
		if !c.IsSet("log-level") && !c.IsSet("l") && c.Bool("debug") {
			log.SetLevel(log.DebugLevel)
		}

		return nil
	}

	if err := app.Run(os.Args); err != nil {
		log.Fatal(err)
	}
}
开发者ID:ZhukovAlexander,项目名称:entropy,代码行数:29,代码来源:main.go


示例18: initLogrus

func initLogrus(ctx *cli.Context) {
	logrus.SetFormatter(&logrus.TextFormatter{
		TimestampFormat: time.RFC822,
		FullTimestamp:   true,
	})

	if level, err := logrus.ParseLevel(ctx.String("log_level")); err == nil {
		logrus.SetLevel(level)
	} else {
		log.Error(err)
		logrus.SetLevel(logrus.InfoLevel)
	}

	filename := ctx.String("log_file")
	logrus.SetOutput(os.Stderr)
	if filename != "" {
		var f *os.File
		_, err := os.Stat(filename)
		if !os.IsNotExist(err) {
			os.Rename(filename, filename+".prev")
		}
		f, err = os.Create(filename)
		if err != nil {
			log.Error("Cannot create log file ", err)
			log.Warning("Continuing to log to stderr")
		} else {
			logrus.SetOutput(f)
		}
	}
}
开发者ID:jaxxstorm,项目名称:fullerite,代码行数:30,代码来源:main.go


示例19: before

func before(c *cli.Context) error {
	// Log level
	if logLevel, err := log.ParseLevel(c.String(LogLevelKey)); err != nil {
		log.Fatal("Failed to parse log level:", err)
	} else {
		log.SetLevel(logLevel)
	}

	if len(c.Args()) != 0 && c.Args().First() != "version" && !c.Bool(HelpKey) && !c.Bool(VersionKey) {
		if err := MachineWorkdir.Set(c.String(WorkdirKey)); err != nil {
			log.Fatalf("Failed to set MachineWorkdir: %s", err)
		}
		if MachineWorkdir.String() == "" {
			log.Fatalln("No Workdir specified!")
		}
	}
	MachineWorkdir.Freeze()

	if err := MachineConfigTypeID.Set(c.String(ConfigTypeIDParamKey)); err != nil {
		log.Fatalf("Failed to set MachineConfigTypeID: %s", err)
	}
	log.Debugf("MachineConfigTypeID: %s", MachineConfigTypeID)

	if err := MachineParamsAdditionalEnvs.Set(c.StringSlice(EnvironmentParamKey)); err != nil {
		log.Fatalf("Failed to set MachineParamsAdditionalEnvs: %s", err)
	}
	log.Debugf("MachineParamsAdditionalEnvs: %s", MachineParamsAdditionalEnvs)
	MachineParamsAdditionalEnvs.Freeze()

	return nil
}
开发者ID:bitrise-tools,项目名称:bitrise-machine,代码行数:31,代码来源:cli.go


示例20: Boot

// Erect the application. Once completed, the application should have
// all the services installed and all the necessary configurations done
// before invoking the deploy sequence. Basically, this method will do
// everything to get the application configured and be ready to launch.
// Method itself however will not launch the app; see Deploy for that.
func (app *App) Boot(env, level, root string) {
	const eenv = "environment name must be 1 word"
	const estat = "could not open the specified root"
	pattern := regexp.MustCompile("^[a-zA-Z0-9]+$")
	parsedLevel, err := logrus.ParseLevel(level)
	if err != nil {
		panic("wrong logging level")
	}
	if !pattern.MatchString(env) {
		panic(eenv)
	}
	if _, e := os.Stat(root); e != nil {
		panic(estat)
	}
	app.RootDirectory = filepath.Clean(root)
	app.Journal = app.makeJournal(parsedLevel)
	app.Env = strings.ToLower(strings.TrimSpace(env))
	app.Config = app.loadConfig(app.Env, "config")
	app.Booted = time.Now()           // mark app as booted
	for _, p := range app.Providers { // setups
		if p.Available[env] { // env available?
			p.Invoked = time.Now()
			p.Setup(app)
		} // setup provider only if availale
	} // all the providers have been invoked
	for _, s := range app.Services {
		s.Up(app)
	}
	log := app.Journal.WithField("env", app.Env)
	log = log.WithField("root", app.RootDirectory)
	log = log.WithField("level", parsedLevel)
	log.Info("application has been booted")
	app.CronEngine.Start() // launch CRON
	app.routers = app.assembleRouters()
}
开发者ID:ts33kr,项目名称:boot,代码行数:40,代码来源:app.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang logrus.Print函数代码示例发布时间:2022-05-28
下一篇:
Golang logrus.Panicf函数代码示例发布时间: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