本文整理汇总了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.")
}
示例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)
}
示例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)
}
}
}
}
示例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() {})
}
示例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
}
示例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
}
示例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
}
示例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 !")
}
示例9: SetLogLevel
func SetLogLevel(levelname string) {
level, err := logrus.ParseLevel(levelname)
if err != nil {
Log.Fatal(err)
}
Log.Level = level
}
示例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
}
示例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)
}
示例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)
}
示例13: Configure
func Configure(loglevel string) {
if level, err := logrus.ParseLevel(loglevel); err != nil {
Logger.Fatal(err)
} else {
Logger.Level = level
}
}
示例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()
}
示例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)
}