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

Golang logrus.Level函数代码示例

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

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



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

示例1: Levels

func (hook *SourceFileHook) Levels() []log.Level {
	levels := make([]log.Level, hook.LogLevel+1)
	for i, _ := range levels {
		levels[i] = log.Level(i)
	}
	return levels
}
开发者ID:tomyhero,项目名称:billie,代码行数:7,代码来源:app.go


示例2: init

func init() {
	var cfgFile string
	flag.StringVar(&cfgFile, "c", "myMon.cfg", "myMon configure file")
	flag.Parse()

	if _, err := os.Stat(cfgFile); err != nil {
		if os.IsNotExist(err) {
			log.WithField("cfg", cfgFile).Fatalf("myMon config file does not exists: %v", err)
		}
	}

	if err := cfg.readConf(cfgFile); err != nil {
		log.Fatalf("Read configure file failed: %v", err)
	}

	// Init log file
	log.SetFormatter(&log.JSONFormatter{})
	log.SetLevel(log.Level(cfg.LogLevel))

	if cfg.LogFile != "" {
		f, err := os.OpenFile(cfg.LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
		if err == nil {
			log.SetOutput(f)
			return
		}
	}
	log.SetOutput(os.Stderr)
}
开发者ID:ZhuoRoger,项目名称:mymon,代码行数:28,代码来源:mpm.go


示例3: Setup

// Setup should be called once at the beginning of the application to
// initialize the package level logger.
func Setup(useSyslog bool, level Level) error {
	if Configured {
		return fmt.Errorf("Application logger has already been configured.")
	}

	if useSyslog {
		// Route normal log output to /dev/null
		log.Out = ioutil.Discard

		// Add syslog hook
		sysLvl, err := syslogLevel(level)
		if err != nil {
			return err
		}
		hook, err := logrus_syslog.NewSyslogHook("", "", sysLvl, "")
		if err != nil {
			return err
		}
		log.Hooks.Add(hook)
	} else {
		log.Out = os.Stdout
		log.Level = logrus.Level(level)
	}

	Configured = true
	return nil
}
开发者ID:jeffizhungry,项目名称:logrus,代码行数:29,代码来源:logsetup.go


示例4: init

func init() {
	c := config.Get()
	l := c.GetInt("log.level")

	Log = log.New()
	Log.Out = os.Stderr
	Log.Level = log.Level(l)
}
开发者ID:LiranCohen,项目名称:quarid-go,代码行数:8,代码来源:logger.go


示例5: InitLogger

// InitLogger ...
func InitLogger(config LoggerConfig) {
	Logger = logrus.New()
	Logger.Level = logrus.Level(config.Level)

	switch config.Adapter {
	case LoggerAdapterConsole:
		Logger.Formatter = &lib.ConsoleFormatter{}
	default:
		Logger.Fatal(ErrLoggerAdapterNotSupported)
	}
}
开发者ID:escribano,项目名称:charon,代码行数:12,代码来源:logger.go


示例6: run

func run(c *cli.Context) error {
	log.SetLevel(log.Level(uint8(c.Int("log-level"))))

	pubsub, err := mqttpubsub.NewBackend(c.String("mqtt-server"), c.String("mqtt-username"), c.String("mqtt-password"))
	if err != nil {
		log.Fatalf("could not setup mqtt backend: %s", err)
	}
	defer pubsub.Close()

	onNew := func(mac lorawan.EUI64) error {
		return pubsub.SubscribeGatewayTX(mac)
	}

	onDelete := func(mac lorawan.EUI64) error {
		return pubsub.UnSubscribeGatewayTX(mac)
	}

	gw, err := gateway.NewBackend(c.String("udp-bind"), onNew, onDelete)
	if err != nil {
		log.Fatalf("could not setup gateway backend: %s", err)
	}
	defer gw.Close()

	go func() {
		for rxPacket := range gw.RXPacketChan() {
			if err := pubsub.PublishGatewayRX(rxPacket.RXInfo.MAC, rxPacket); err != nil {
				log.Errorf("could not publish RXPacket: %s", err)
			}
		}
	}()

	go func() {
		for stats := range gw.StatsChan() {
			if err := pubsub.PublishGatewayStats(stats.MAC, stats); err != nil {
				log.Errorf("could not publish GatewayStatsPacket: %s", err)
			}
		}
	}()

	go func() {
		for txPacket := range pubsub.TXPacketChan() {
			if err := gw.Send(txPacket); err != nil {
				log.Errorf("could not send TXPacket: %s", err)
			}
		}
	}()

	sigChan := make(chan os.Signal)
	signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
	log.WithField("signal", <-sigChan).Info("signal received")
	log.Warning("shutting down server")
	return nil
}
开发者ID:RedBeardLab,项目名称:lora-semtech-bridge,代码行数:53,代码来源:main.go


示例7: InitLog

func InitLog(cfg *Cfg) {
	// Init log file
	log.SetFormatter(&log.JSONFormatter{})
	log.SetLevel(log.Level(cfg.LogLevel))

	if cfg.LogFile != "" {
		f, err := os.OpenFile(cfg.LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
		if err == nil {
			log.SetOutput(f)
			return
		}
	}
	log.SetOutput(os.Stderr)
}
开发者ID:onlymellb,项目名称:mysql-monitor,代码行数:14,代码来源:func.go


示例8: getConfig

func getConfig(flagset *flag.FlagSet, userCfgFile string) (*config.Config, error) {
	opts := globalconf.Options{EnvPrefix: "API_HOSTD_"}

	if userCfgFile != "" {
		// Fail hard if a user-provided config is not usable
		fi, err := os.Stat(userCfgFile)
		if err != nil {
			ctxLog.Fatalf("Unable to use config file %s: %v", userCfgFile, err)
		}
		if fi.IsDir() {
			ctxLog.Fatalf("Provided config %s is a directory, not a file", userCfgFile)
		}
		opts.Filename = userCfgFile
	} else if _, err := os.Stat(DefaultConfigFile); err == nil {
		opts.Filename = DefaultConfigFile
	}

	gconf, err := globalconf.NewWithOptions(&opts)
	if err != nil {
		return nil, err
	}

	gconf.ParseSet("", flagset)

	cfg := config.Config{
		Verbosity: (*flagset.Lookup("verbosity")).Value.(flag.Getter).Get().(int),
		IP:        (*flagset.Lookup("ip")).Value.(flag.Getter).Get().(string),
		Port:      (*flagset.Lookup("port")).Value.(flag.Getter).Get().(string),
		Secret:    (*flagset.Lookup("jwt_sign_key")).Value.(flag.Getter).Get().(string),

		CORSAllowedOrigins:     config.StringToSlice((*flagset.Lookup("cors_allowed_origins")).Value.(flag.Getter).Get().(string)),
		CORSAllowedMethods:     config.StringToSlice((*flagset.Lookup("cors_allowed_methods")).Value.(flag.Getter).Get().(string)),
		CORSAllowedHeaders:     config.StringToSlice((*flagset.Lookup("cors_allowed_headers")).Value.(flag.Getter).Get().(string)),
		CORSExposedHeaders:     config.StringToSlice((*flagset.Lookup("cors_exposed_headers")).Value.(flag.Getter).Get().(string)),
		CORSAllowCredentials:   (*flagset.Lookup("cors_allow_credentials")).Value.(flag.Getter).Get().(bool),
		CORSMaxAge:             (*flagset.Lookup("cors_max_age")).Value.(flag.Getter).Get().(int),
		CORSOptionsPassThrough: (*flagset.Lookup("cors_options_pass_through")).Value.(flag.Getter).Get().(bool),
		CORSDebug:              (*flagset.Lookup("cors_debug")).Value.(flag.Getter).Get().(bool),
	}

	log.SetLevel(log.Level(cfg.Verbosity))

	ctxLog.Infof("Loaded config: [%+v]", cfg)

	return &cfg, nil
}
开发者ID:nildev,项目名称:api-host,代码行数:46,代码来源:api-host.go


示例9: setConfig

func setConfig(config *HiveConfig) (*schedule.GlobalConfigStruct, string, string) {
	maxprocs := config.Maxprocs
	port := config.Port
	managerport := config.ManagerPort
	loglevel := config.Loglevel
	cpuProfName := config.CpuProfName
	memProfName := config.MemProfName

	runtime.GOMAXPROCS(maxprocs)

	dg := schedule.DefaultGlobal()
	dg.L.Level = logrus.Level(loglevel)
	dg.Port = ":" + port
	dg.ManagerPort = ":" + managerport

	return dg, cpuProfName, memProfName
}
开发者ID:rprp,项目名称:hivego,代码行数:17,代码来源:hive.go


示例10: run

func run(c *cli.Context) {
	var (
		flag uint32
		tpl  *template.Template
		ctx  = context.Background()
	)
	if !c.Args().Present() {
		cli.ShowAppHelp(c)
		return
	}

	log.SetLevel(log.Level(c.Int("verbose")))

	watcher, err := inotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}

	// Format.
	if fmtString := c.String("format"); fmtString != "" {
		tpl = template.Must(template.New("event-format").Parse(fmtString))
	}

	// Event flags.
	for _, event := range c.StringSlice("event") {
		flag |= parseEvent(event)
	}
	if flag == 0 {
		flag = inotify.IN_ALL_EVENTS
	}

	watch(watcher, c.Args(), flag, c.Bool("recursive"), true)

	// Configure timeout.
	if timeout := time.Duration(c.Int("timeout")) * time.Second; timeout > 0 {
		ctx, _ = context.WithTimeout(ctx, timeout)
	}

	match := buildMatcherFunc(c.StringSlice("exclude"), c.StringSlice("include"))
	waitForWatcher(ctx, watcher, match, tpl, c.Bool("monitor"))
}
开发者ID:ceram1,项目名称:gonotify,代码行数:41,代码来源:main.go


示例11: upgrade

func upgrade(context *cli.Context) {
	verbosity = context.Int("verbosity")
	if !context.IsSet("verbosity") {
		if verbosity < 2 {
			verbosity = 2
		}
	}
	spirit.Logger().Level = logrus.Level(verbosity)

	var err error

	defer func() {
		if err != nil {
			spirit.Logger().Error(err)
			os.Exit(128)
		}
	}()

	var out []byte
	cmd := "go get -u github.com/gogap/spirit-tool"
	if verbosity > 0 {
		cmd = "go get -v -u github.com/gogap/spirit-tool"
	}
	if out, err = execCommand(cmd); err != nil {
		spirit.Logger().Errorln(err)
		return
	}
	spirit.Logger().Infoln(out)

	cmd = "go install github.com/gogap/spirit-tool"
	if verbosity > 0 {
		cmd = "go install -v github.com/gogap/spirit-tool"
	}
	if out, err = execCommand(cmd); err != nil {
		spirit.Logger().Errorln(err)
		return
	}
	spirit.Logger().Infoln(out)

	return
}
开发者ID:gogap,项目名称:spirit-tool,代码行数:41,代码来源:main.go


示例12: NewCluster

// NewCluster returns a new cluster with the given config
func NewCluster(config Config) (*Cluster, error) {
	logger := logrus.New()
	logger.Out = config.LogOutput
	logger.Level = logrus.Level(config.LogLevel)

	if config.SerfConfig == nil {
		return nil, fmt.Errorf("Config.SerfConfig cannot be nil")
	}
	if config.SerfConfig.EventCh != nil {
		return nil, fmt.Errorf("SerfConfig.EventCh must be nil (try using Config.SerfEvents instead)")
	}

	memberMap := make(map[string]*serf.Member)
	memberMutex := sync.Mutex{}

	ring := &ring{members: make([]*serf.Member, 0, 0)}

	serfEvents := make(chan serf.Event, 256)
	config.SerfConfig.EventCh = serfEvents
	nodeSerf, err := serf.Create(config.SerfConfig)
	if err != nil {
		return nil, fmt.Errorf("Unable to create serf: %v", err)
	}

	exit := make(chan bool)

	cluster := &Cluster{
		exit:        exit,
		config:      config,
		memberMap:   memberMap,
		ring:        ring,
		memberMutex: memberMutex,
		serfEvents:  serfEvents,
		Serf:        nodeSerf,
		logger:      logger,
	}

	return cluster, nil
}
开发者ID:bpot,项目名称:libring,代码行数:40,代码来源:cluster.go


示例13: main

func main() {
	flag.Usage = usage
	flag.Parse()

	if debug {
		go debugServer(DebugAddress)
	}

	ctx := context.Background()

	filename := filepath.Base(configFile)
	ext := filepath.Ext(configFile)
	configPath := filepath.Dir(configFile)

	viper.SetConfigType(strings.TrimPrefix(ext, "."))
	viper.SetConfigName(strings.TrimSuffix(filename, ext))
	viper.AddConfigPath(configPath)
	err := viper.ReadInConfig()
	if err != nil {
		logrus.Error("Viper Error: ", err.Error())
		logrus.Error("Could not read config at ", configFile)
		os.Exit(1)
	}
	logrus.SetLevel(logrus.Level(viper.GetInt("logging.level")))

	sigHup := make(chan os.Signal)
	sigTerm := make(chan os.Signal)

	signal.Notify(sigHup, syscall.SIGHUP)
	signal.Notify(sigTerm, syscall.SIGTERM)

	var trust signed.CryptoService
	if viper.GetString("trust_service.type") == "remote" {
		logrus.Info("[Notary Server] : Using remote signing service")
		trust = signer.NewRufusSigner(
			viper.GetString("trust_service.hostname"),
			viper.GetString("trust_service.port"),
			viper.GetString("trust_service.tls_ca_file"),
		)
	} else {
		logrus.Info("[Notary Server] : Using local signing service")
		trust = signed.NewEd25519()
	}

	if viper.GetString("store.backend") == "mysql" {
		dbURL := viper.GetString("storage.db_url")
		db, err := sql.Open("mysql", dbURL)
		if err != nil {
			logrus.Fatal("[Notary Server] Error starting DB driver: ", err.Error())
			return // not strictly needed but let's be explicit
		}
		ctx = context.WithValue(ctx, "metaStore", storage.NewMySQLStorage(db))
	} else {
		ctx = context.WithValue(ctx, "metaStore", storage.NewMemStorage())
	}
	logrus.Info("[Notary Server] Starting Server")
	err = server.Run(
		ctx,
		viper.GetString("server.addr"),
		viper.GetString("server.tls_cert_file"),
		viper.GetString("server.tls_key_file"),
		trust,
	)

	logrus.Error("[Notary Server]", err.Error())
	return
}
开发者ID:aaronlehmann,项目名称:notary,代码行数:67,代码来源:main.go


示例14: main

func main() {
	flag.Usage = usage
	flag.Parse()

	if debug {
		go debugServer(debugAddr)
	}

	// when the signer starts print the version for debugging and issue logs later
	logrus.Infof("Version: %s, Git commit: %s", version.NotaryVersion, version.GitCommit)

	filename := filepath.Base(configFile)
	ext := filepath.Ext(configFile)
	configPath := filepath.Dir(configFile)

	viper.SetConfigType(strings.TrimPrefix(ext, "."))
	viper.SetConfigName(strings.TrimSuffix(filename, ext))
	viper.AddConfigPath(configPath)
	err := viper.ReadInConfig()
	if err != nil {
		logrus.Error("Viper Error: ", err.Error())
		logrus.Error("Could not read config at ", configFile)
		os.Exit(1)
	}

	logrus.SetLevel(logrus.Level(viper.GetInt("logging.level")))

	certFile := viper.GetString("server.cert_file")
	keyFile := viper.GetString("server.key_file")
	if certFile == "" || keyFile == "" {
		usage()
		log.Fatalf("Certificate and key are mandatory")
	}

	tlsConfig := &tls.Config{
		MinVersion:               tls.VersionTLS12,
		PreferServerCipherSuites: true,
		CipherSuites: []uint16{
			tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
			tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
			tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
			tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
			tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
			tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
			tls.TLS_RSA_WITH_AES_128_CBC_SHA,
			tls.TLS_RSA_WITH_AES_256_CBC_SHA},
	}
	tlsConfig.Rand = rand.Reader

	cryptoServices := make(signer.CryptoServiceIndex)

	pin := viper.GetString(pinCode)
	pkcs11Lib := viper.GetString("crypto.pkcs11lib")
	if pkcs11Lib != "" {
		if pin == "" {
			log.Fatalf("Using PIN is mandatory with pkcs11")
		}

		ctx, session := SetupHSMEnv(pkcs11Lib, pin)

		defer cleanup(ctx, session)

		cryptoServices[data.RSAKey] = api.NewRSAHardwareCryptoService(ctx, session)
	}

	configDBType := strings.ToLower(viper.GetString("storage.backend"))
	dbURL := viper.GetString("storage.db_url")
	if configDBType != dbType || dbURL == "" {
		usage()
		log.Fatalf("Currently only a MySQL database backend is supported.")
	}
	dbSQL, err := sql.Open(configDBType, dbURL)
	if err != nil {
		log.Fatalf("failed to open the database: %s, %v", dbURL, err)
	}

	defaultAlias := viper.GetString(defaultAliasEnv)
	logrus.Debug("Default Alias: ", defaultAlias)
	keyStore, err := signer.NewKeyDBStore(passphraseRetriever, defaultAlias, configDBType, dbSQL)
	if err != nil {
		log.Fatalf("failed to create a new keydbstore: %v", err)
	}
	cryptoService := cryptoservice.NewCryptoService("", keyStore)

	cryptoServices[data.ED25519Key] = cryptoService
	cryptoServices[data.ECDSAKey] = cryptoService

	//RPC server setup
	kms := &api.KeyManagementServer{CryptoServices: cryptoServices}
	ss := &api.SignerServer{CryptoServices: cryptoServices}

	grpcServer := grpc.NewServer()
	pb.RegisterKeyManagementServer(grpcServer, kms)
	pb.RegisterSignerServer(grpcServer, ss)

	rpcAddr := viper.GetString("server.grpc_addr")
	lis, err := net.Listen("tcp", rpcAddr)
	if err != nil {
		log.Fatalf("failed to listen %v", err)
	}
//.........这里部分代码省略.........
开发者ID:hellonicky,项目名称:notary,代码行数:101,代码来源:main.go


示例15: SetLoggerTo

func SetLoggerTo(logLevel int) {
	log.SetLevel(log.Level(logLevel))
}
开发者ID:gitter-badger,项目名称:getme,代码行数:3,代码来源:config.go


示例16: NewArg

func NewArg(logLevel int) Arg {
	return Arg{
		LogLevel:            log.Level(logLevel),
		PingTimeoutDuration: PingTimeoutDurationDefault,
	}
}
开发者ID:IRCody,项目名称:snap,代码行数:6,代码来源:plugin.go


示例17: main

func main() {
	flag.Usage = usage
	flag.Parse()

	if DebugAddress != "" {
		go debugServer(DebugAddress)
	}

	ctx := context.Background()

	conf, err := parseConfig(configFile)
	if err != nil {
		logrus.Fatal("Error parsing config: ", err.Error())
		return // not strictly needed but let's be explicit
	}
	if conf.Logging.Level > 0 {
		logrus.SetLevel(logrus.Level(conf.Logging.Level))
	}

	sigHup := make(chan os.Signal)
	sigTerm := make(chan os.Signal)

	signal.Notify(sigHup, syscall.SIGHUP)
	signal.Notify(sigTerm, syscall.SIGTERM)

	var trust signed.CryptoService
	if conf.TrustService.Type == "remote" {
		logrus.Info("[Notary Server] : Using remote signing service")
		trust = signer.NewRufusSigner(conf.TrustService.Hostname, conf.TrustService.Port, conf.TrustService.TLSCAFile)
	} else {
		logrus.Info("[Notary Server] : Using local signing service")
		trust = signed.NewEd25519()
	}

	db, err := sql.Open("mysql", "dockercondemo:[email protected](notarymysql:3306)/dockercondemo")
	if err != nil {
		logrus.Fatal("Error starting DB driver: ", err.Error())
		return // not strictly needed but let's be explicit
	}
	ctx = context.WithValue(ctx, "versionStore", storage.NewMySQLStorage(db))
	for {
		logrus.Info("[Notary Server] Starting Server")
		childCtx, cancel := context.WithCancel(ctx)
		go server.Run(childCtx, conf.Server, trust)

		for {
			select {
			// On a sighup we cancel and restart a new server
			// with updated config
			case <-sigHup:
				logrus.Infof("[Notary Server] Server restart requested. Attempting to parse config at %s", configFile)
				conf, err = parseConfig(configFile)
				if err != nil {
					logrus.Infof("[Notary Server] Unable to parse config. Old configuration will keep running. Parse Err: %s", err.Error())
					continue
				} else {
					cancel()
					logrus.Info("[Notary Server] Stopping server for restart")
					break
				}
			// On sigkill we cancel and shutdown
			case <-sigTerm:
				cancel()
				logrus.Info("[Notary Server] Shutting Down Hard")
				os.Exit(0)
			}
		}
	}
}
开发者ID:progrium,项目名称:notary,代码行数:69,代码来源:main.go


示例18: main

func main() {
	var debugLevel = uint(logrus.InfoLevel)
	flag.StringVar(&configFileName, "config", configFileName, "configuration `fileName`")
	flag.UintVar(&debugLevel, "level", debugLevel, "log `level` [0-5]")
	flag.Parse() // разбираем параметры запуска приложения

	logrus.SetLevel(logrus.Level(debugLevel)) // уровень отладки
	// logrus.SetFormatter(new(logrus.JSONFormatter))
	logrus.SetFormatter(new(prefixed.TextFormatter))
	// hook, err := logrus_syslog.NewSyslogHook("", "", syslog.LOG_INFO, "")
	// if err == nil {
	// 	logrus.AddHook(hook)
	// }

	// выводим в лог информацию о приложении и версии
	logEntry := llog.WithField("version", version)
	if build != "" { // добавляем билд к номеру версии
		logEntry = logEntry.WithField("build", build)
	}
	if date != "" { // добавляем дату сборки к версии
		logEntry = logEntry.WithField("buildDate", date)
	}
	logEntry.Info(appName)

	// запускаем бесконечный цикл чтения конфигурации и установки соединения
	for {
		// загружаем и разбираем конфигурационный файл
		logEntry := llog.WithField("filename", configFileName)
		var err error
		config, err = LoadConfig(configFileName) // загружаем конфигурационный файл
		if err != nil {
			logEntry.WithError(err).Fatal("Error loading config")
		}
		logEntry.WithField("mx", len(config.MX)).Info("Config loaded")

		sglogDB, err = sqlog.Connect(config.SMSGate.MYSQL)
		if err != nil {
			logEntry.WithError(err).Fatal("Error connecting to MySQL")
		}
		// zabbixLog = zabbix.New(config.SMSGate.ZabbixHost)
		zabbixLog = config.SMSGate.SMPP.Zabbix
		zabEntry := llog.WithField("host", zabbixLog.Host)
		zabEntry.WithField("server", zabbixLog.Server).Info("Zabbix")
		// zabbixLog.Send("gw.sms.unknown.destination", "79670238554")

		config.SMSGate.SMPP.Zabbix = config.SMSGate.Zabbix

		config.MXConnect()       // запускаем асинхронно соединение с MX
		config.SMSGate.Connect() // устанавливаем соединение с SMPP серверами
		// инициализируем поддержку системных сигналов и ждем, когда он случится...
		signal := monitorSignals(os.Interrupt, os.Kill, syscall.SIGUSR1)
		config.SMSGate.Close() // останавливаем соединение с SMPP
		config.MXClose()       // останавливаем соединение с MX серверами
		sglogDB.Close()        // закрываем соединение с логом
		// проверяем, что сигнал не является сигналом перечитать конфиг
		if signal != syscall.SIGUSR1 {
			llog.Info("The end")
			return // заканчиваем нашу работу
		}
		llog.Info("Reload") // перечитываем конфиг и начинаем все с начала
	}
}
开发者ID:mdigger,项目名称:mxsms2,代码行数:62,代码来源:main.go


示例19: main

func main() {
	flag.Usage = usage
	flag.Parse()

	if debug {
		go debugServer(debugAddr)
	}

	// when the signer starts print the version for debugging and issue logs later
	logrus.Infof("Version: %s, Git commit: %s", version.NotaryVersion, version.GitCommit)

	filename := filepath.Base(configFile)
	ext := filepath.Ext(configFile)
	configPath := filepath.Dir(configFile)

	mainViper.SetConfigType(strings.TrimPrefix(ext, "."))
	mainViper.SetConfigName(strings.TrimSuffix(filename, ext))
	mainViper.AddConfigPath(configPath)
	err := mainViper.ReadInConfig()
	if err != nil {
		logrus.Error("Viper Error: ", err.Error())
		logrus.Error("Could not read config at ", configFile)
		os.Exit(1)
	}

	logrus.SetLevel(logrus.Level(mainViper.GetInt("logging.level")))

	tlsConfig, err := signerTLS(mainViper, true)
	if err != nil {
		logrus.Fatalf(err.Error())
	}

	cryptoServices := make(signer.CryptoServiceIndex)

	configDBType := strings.ToLower(mainViper.GetString("storage.backend"))
	dbURL := mainViper.GetString("storage.db_url")
	if configDBType != dbType || dbURL == "" {
		usage()
		log.Fatalf("Currently only a MySQL database backend is supported.")
	}
	dbSQL, err := sql.Open(configDBType, dbURL)
	if err != nil {
		log.Fatalf("failed to open the database: %s, %v", dbURL, err)
	}

	defaultAlias := mainViper.GetString(defaultAliasEnv)
	logrus.Debug("Default Alias: ", defaultAlias)
	keyStore, err := keydbstore.NewKeyDBStore(passphraseRetriever, defaultAlias, configDBType, dbSQL)
	if err != nil {
		log.Fatalf("failed to create a new keydbstore: %v", err)
	}

	health.RegisterPeriodicFunc(
		"DB operational", keyStore.HealthCheck, time.Second*60)

	cryptoService := cryptoservice.NewCryptoService("", keyStore)

	cryptoServices[data.ED25519Key] = cryptoService
	cryptoServices[data.ECDSAKey] = cryptoService

	//RPC server setup
	kms := &api.KeyManagementServer{CryptoServices: cryptoServices,
		HealthChecker: health.CheckStatus}
	ss := &api.SignerServer{CryptoServices: cryptoServices,
		HealthChecker: health.CheckStatus}

	rpcAddr := mainViper.GetString("server.grpc_addr")
	lis, err := net.Listen("tcp", rpcAddr)
	if err != nil {
		log.Fatalf("failed to listen %v", err)
	}
	creds := credentials.NewTLS(tlsConfig)
	opts := []grpc.ServerOption{grpc.Creds(creds)}
	grpcServer := grpc.NewServer(opts...)

	pb.RegisterKeyManagementServer(grpcServer, kms)
	pb.RegisterSignerServer(grpcServer, ss)

	go grpcServer.Serve(lis)

	httpAddr := mainViper.GetString("server.http_addr")
	if httpAddr == "" {
		log.Fatalf("Server address is required")
	}
	//HTTP server setup
	server := http.Server{
		Addr:      httpAddr,
		Handler:   api.Handlers(cryptoServices),
		TLSConfig: tlsConfig,
	}

	if debug {
		log.Println("RPC server listening on", rpcAddr)
		log.Println("HTTP server listening on", httpAddr)
	}

	err = server.ListenAndServeTLS("", "")
	if err != nil {
		log.Fatal("HTTPS server failed to start:", err)
	}
//.........这里部分代码省略.........
开发者ID:runcom,项目名称:notary,代码行数:101,代码来源:main.go


示例20: SetLogLevel

// SetLevel sets the standard logger level.
func SetLogLevel(level Level) {
	log.SetLevel(log.Level(level))
	log.Debugf("SetLogLevel(): %s", log.GetLevel().String())
}
开发者ID:polyverse-security,项目名称:appconfig,代码行数:5,代码来源:config.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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