當前位置: 首頁>>代碼示例>>Golang>>正文


Golang logrus.ParseLevel函數代碼示例

本文整理匯總了Golang中github.com/Sirupsen/logrus.ParseLevel函數的典型用法代碼示例。如果您正苦於以下問題:Golang ParseLevel函數的具體用法?Golang ParseLevel怎麽用?Golang ParseLevel使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了ParseLevel函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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


注:本文中的github.com/Sirupsen/logrus.ParseLevel函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。