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

Golang logrus.SetFormatter函数代码示例

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

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



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

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


示例2: ConfigureLogging

func ConfigureLogging(level, format string, output io.Writer) error {
	switch level {
	case "debug":
		log.SetLevel(log.DebugLevel)
	case "info":
		log.SetLevel(log.InfoLevel)
	case "warn":
		log.SetLevel(log.WarnLevel)
	case "error":
		log.SetLevel(log.ErrorLevel)
	case "fatal":
		log.SetLevel(log.FatalLevel)
	case "panic":
		log.SetLevel(log.PanicLevel)
	default:
		return errors.New("Invalid log level: " + level)
	}

	switch format {
	case "text":
		log.SetFormatter(&log.TextFormatter{
			TimestampFormat: time.RFC3339,
			FullTimestamp:   true,
		})
	case "json":
		log.SetFormatter(&log.JSONFormatter{
			TimestampFormat: time.RFC3339,
		})
	default:
		return errors.New("Invalid format type: " + format)
	}
	log.SetOutput(output)
	return nil

}
开发者ID:ranjib,项目名称:Gypsy,代码行数:35,代码来源:log.go


示例3: Manage

func (service *Service) Manage() (string, error) {
	usage := "Usage: metronome install | remove | start | stop | status | agent\n"

	if flag.NArg() > 0 {
		switch flag.Args()[0] {
		case "install":
			return service.Install()
		case "remove":
			return service.Remove()
		case "start":
			return service.Start()
		case "stop":
			return service.Stop()
		case "status":
			return service.Status()
		case "agent":
			return agent()
		case "push":
			return scheduler.Push()
		case "dispatch":
			return dispatch(flag.Args()[1])
		case "version":
			log.SetFormatter(&util.SimpleFormatter{})
			return fmt.Sprintf("metronome %s\n", Version), nil
		default:
			log.SetFormatter(&util.SimpleFormatter{})
			return usage, nil
		}
	}
	return agent()
}
开发者ID:cloudconductor,项目名称:metronome,代码行数:31,代码来源:service.go


示例4: configureLogging

func configureLogging(v *viper.Viper) {
	level, err := log.ParseLevel(v.GetString("log_level"))
	if err != nil {
		log.Fatalln(err)
	}
	log.SetLevel(level)

	if v.GetString("log_format") == "text" {
		log.SetFormatter(&log.TextFormatter{DisableColors: true, FullTimestamp: true})
	} else if v.GetString("log_format") == "json" {
		log.SetFormatter(&log.JSONFormatter{})
	} else {
		log.Errorln("Error: log_type invalid, defaulting to text")
		log.SetFormatter(&log.TextFormatter{})
	}
	switch v.GetString("log_target") {
	case "stdout":
		log.SetOutput(os.Stdout)
	case "stderr":
		log.SetOutput(os.Stderr)
	default:
		log.Errorln("Error: log_target invalid, defaulting to Stdout")
		log.SetOutput(os.Stdout)
	}
}
开发者ID:pandemicsyn,项目名称:stalker,代码行数:25,代码来源:main.go


示例5: run

func run() {
	fmtlog.SetFlags(fmtlog.Lshortfile | fmtlog.LstdFlags)

	// load global configuration
	globalConfiguration := LoadConfiguration()

	loggerMiddleware := middlewares.NewLogger(globalConfiguration.AccessLogsFile)
	defer loggerMiddleware.Close()

	// logging
	level, err := log.ParseLevel(strings.ToLower(globalConfiguration.LogLevel))
	if err != nil {
		log.Fatal("Error getting level", err)
	}
	log.SetLevel(level)

	if len(globalConfiguration.TraefikLogsFile) > 0 {
		fi, err := os.OpenFile(globalConfiguration.TraefikLogsFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
		defer fi.Close()
		if err != nil {
			log.Fatal("Error opening file", err)
		} else {
			log.SetOutput(fi)
			log.SetFormatter(&log.TextFormatter{DisableColors: true, FullTimestamp: true, DisableSorting: true})
		}
	} else {
		log.SetFormatter(&log.TextFormatter{FullTimestamp: true, DisableSorting: true})
	}
	log.Debugf("Global configuration loaded %+v", globalConfiguration)
	server := NewServer(*globalConfiguration)
	server.Start()
	defer server.Close()
	log.Info("Shutting down")
}
开发者ID:dontrebootme,项目名称:traefik,代码行数:34,代码来源:cmd.go


示例6: InitLog

// InitLog initializes the logrus logger
func InitLog(logLevel, formatter string) error {

	switch formatter {
	case LogStashFormatter:
		logrus.SetFormatter(&logstash.LogstashFormatter{
			TimestampFormat: time.RFC3339,
		})
	default:
		logrus.SetFormatter(&logrus.TextFormatter{
			ForceColors:   true,
			FullTimestamp: true,
		})
	}

	logrus.SetOutput(os.Stdout)

	level, err := logrus.ParseLevel(logLevel)

	if err != nil {
		logrus.SetLevel(logrus.DebugLevel)
		return err
	}

	logrus.SetLevel(level)
	return nil
}
开发者ID:sebastienfr,项目名称:handsongo,代码行数:27,代码来源:logger.go


示例7: ResponseLogAndError

// ResponseLogAndError would log the error before call ResponseError()
func ResponseLogAndError(v interface{}) {
	if e, ok := v.(*logrus.Entry); ok {
		e.Error(e.Message)
		oldFormatter := e.Logger.Formatter
		logrus.SetFormatter(&logrus.JSONFormatter{})
		s, err := e.String()
		logrus.SetFormatter(oldFormatter)
		if err != nil {
			ResponseError(err.Error())
			return
		}
		// Cosmetic since " would be escaped
		ResponseError(strings.Replace(s, "\"", "'", -1))
	} else {
		e, isErr := v.(error)
		_, isRuntimeErr := e.(runtime.Error)
		if isErr && !isRuntimeErr {
			logrus.Errorf(fmt.Sprint(e))
			ResponseError(fmt.Sprint(e))
		} else {
			logrus.Errorf("Caught FATAL error: %s", v)
			debug.PrintStack()
			ResponseError("Caught FATAL error: %s", v)
		}
	}
}
开发者ID:rancher,项目名称:convoy-agent,代码行数:27,代码来源:response.go


示例8: NewCustomizedLogger

func NewCustomizedLogger(level string, developerModeFlag bool) (*log.Logger, error) {
	logger := log.New()

	lv, err := log.ParseLevel(level)
	if err != nil {
		return nil, err
	}
	logger.Level = lv

	if developerModeFlag {
		customFormatter := new(log.TextFormatter)
		customFormatter.FullTimestamp = true
		customFormatter.TimestampFormat = "2006-01-02 15:04:05"
		log.SetFormatter(customFormatter)

		log.SetLevel(log.DebugLevel)
		logger.Level = lv
		logger.Formatter = customFormatter
	} else {
		customFormatter := new(log.JSONFormatter)
		customFormatter.TimestampFormat = "2006-01-02 15:04:05"

		log.SetFormatter(customFormatter)
		customFormatter.DisableTimestamp = false

		log.SetLevel(log.InfoLevel)
		logger.Level = lv
		logger.Formatter = customFormatter
	}

	logger.Out = os.Stdout

	return logger, nil
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:34,代码来源:log.go


示例9: InitializeLogger

func InitializeLogger(developerModeFlag bool) {
	logger = log.New()

	if developerModeFlag {
		customFormatter := new(log.TextFormatter)
		customFormatter.FullTimestamp = true
		customFormatter.TimestampFormat = "2006-01-02 15:04:05"
		log.SetFormatter(customFormatter)

		log.SetLevel(log.DebugLevel)
		logger.Level = log.DebugLevel
		logger.Formatter = customFormatter
	} else {
		customFormatter := new(log.JSONFormatter)
		customFormatter.TimestampFormat = "2006-01-02 15:04:05"

		log.SetFormatter(customFormatter)
		customFormatter.DisableTimestamp = false

		log.SetLevel(log.InfoLevel)
		logger.Level = log.InfoLevel
		logger.Formatter = customFormatter
	}

	logger.Out = os.Stdout

}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:27,代码来源:log.go


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


示例11: main

func main() {

	// configure logging
	logrus.SetLevel(logrus.InfoLevel)
	logrus.SetFormatter(&logrus.TextFormatter{FullTimestamp: true})

	// options to change log level
	globalOptions.Quiet = func() {
		logrus.SetLevel(logrus.WarnLevel)
	}
	globalOptions.Verbose = func() {
		logrus.SetLevel(logrus.DebugLevel)
	}
	globalOptions.LogJSON = func() {
		logrus.SetFormatter(&logrus.JSONFormatter{})
	}
	globalOptions.LogSyslog = func() {
		setupSyslog()
	}

	originalArgs = os.Args
	if _, err := parser.Parse(); err != nil {
		os.Exit(1)
	}
}
开发者ID:justone,项目名称:pmb,代码行数:25,代码来源:main.go


示例12: setupLogging

func setupLogging() {
	switch viper.GetString("log-level") {
	case "debug":
		log.SetLevel(log.DebugLevel)
	case "info":
		log.SetLevel(log.InfoLevel)
	case "warn":
		log.SetLevel(log.WarnLevel)
	case "error":
		log.SetLevel(log.ErrorLevel)
	case "fatal":
		log.SetLevel(log.FatalLevel)
	default:
		log.WithField("log-level", viper.GetString("log-level")).Warning("invalid log level. defaulting to info.")
		log.SetLevel(log.InfoLevel)
	}

	switch viper.GetString("log-format") {
	case "text":
		log.SetFormatter(new(log.TextFormatter))
	case "json":
		log.SetFormatter(new(log.JSONFormatter))
	default:
		log.WithField("log-format", viper.GetString("log-format")).Warning("invalid log format. defaulting to text.")
		log.SetFormatter(new(log.TextFormatter))
	}
}
开发者ID:nikolayvoronchikhin,项目名称:mantl-api,代码行数:27,代码来源:main.go


示例13: initLogger

func initLogger() {
	if strings.ToUpper(config.OutputFormat) == "JSON" {
		log.SetFormatter(&log.JSONFormatter{})
	} else {
		// The TextFormatter is default, you don't actually have to do this.
		log.SetFormatter(&log.TextFormatter{})
	}
}
开发者ID:andrewmichaelsmith,项目名称:rabbitmq_exporter,代码行数:8,代码来源:main.go


示例14: ConfigureLogger

func ConfigureLogger() {
	switch viper.GetString("ENV") {
	case "DEVELOPMENT":
		log.SetFormatter(&log.TextFormatter{ForceColors: true})
	case "PRODUCTION":
		log.SetFormatter(&log.JSONFormatter{})
	default:
		log.SetFormatter(&log.TextFormatter{})
	}
}
开发者ID:alligrader,项目名称:gradebook-backend,代码行数:10,代码来源:util.go


示例15: configureLogging

// configureLogging prepares the context with a logger using the
// configuration.
func configureLogging(ctx context.Context, config *configuration.Configuration) (context.Context, error) {
	if config.Log.Level == "" && config.Log.Formatter == "" {
		// If no config for logging is set, fallback to deprecated "Loglevel".
		log.SetLevel(logLevel(config.Loglevel))
		ctx = context.WithLogger(ctx, context.GetLogger(ctx, "version"))
		return ctx, nil
	}

	log.SetLevel(logLevel(config.Log.Level))

	formatter := config.Log.Formatter
	if formatter == "" {
		formatter = "text" // default formatter
	}

	switch formatter {
	case "json":
		log.SetFormatter(&log.JSONFormatter{
			TimestampFormat: time.RFC3339Nano,
		})
	case "text":
		log.SetFormatter(&log.TextFormatter{
			TimestampFormat: time.RFC3339Nano,
		})
	case "logstash":
		log.SetFormatter(&logstash.LogstashFormatter{
			TimestampFormat: time.RFC3339Nano,
		})
	default:
		// just let the library use default on empty string.
		if config.Log.Formatter != "" {
			return ctx, fmt.Errorf("unsupported logging formatter: %q", config.Log.Formatter)
		}
	}

	if config.Log.Formatter != "" {
		log.Debugf("using %q logging formatter", config.Log.Formatter)
	}

	// log the application version with messages
	ctx = context.WithLogger(ctx, context.GetLogger(ctx, "version"))

	if len(config.Log.Fields) > 0 {
		// build up the static fields, if present.
		var fields []interface{}
		for k := range config.Log.Fields {
			fields = append(fields, k)
		}

		ctx = context.WithValues(ctx, config.Log.Fields)
		ctx = context.WithLogger(ctx, context.GetLogger(ctx, fields...))
	}

	return ctx, nil
}
开发者ID:orivej,项目名称:distribution,代码行数:57,代码来源:main.go


示例16: init

func init() {
	// set this if environment is production
	log.SetFormatter(&log.JSONFormatter{})
	// set this for non prod
	log.SetFormatter(&log.TextFormatter{})

	// Output to stderr instead of stdout, could also be a file.
	log.SetOutput(os.Stderr)

	// Only log the warning severity or above.
	log.SetLevel(log.DebugLevel)
}
开发者ID:elarasu,项目名称:basis,代码行数:12,代码来源:logger.go


示例17: main

func main() {
	// Output to stderr instead of stdout, could also be a file.
	log.SetOutput(os.Stderr)

	// getting configuration
	file, err := os.Open("conf.json")
	if err != nil {
		log.Panic("Failed to open configuration file, quiting server.")
	}
	decoder := json.NewDecoder(file)
	StuboConfig = Configuration{}
	err = decoder.Decode(&StuboConfig)
	if err != nil {
		log.WithFields(log.Fields{"Error": err.Error()}).Panic("Failed to read configuration")
	}
	// configuring logger based on environment settings
	if StuboConfig.Environment == "production" {
		// Log as JSON instead of the default ASCII formatter.
		log.SetFormatter(&log.JSONFormatter{})
		// TODO: also, write to file, probably log file path should also be configurable
	} else {
		// The TextFormatter is default
		log.SetFormatter(&log.TextFormatter{})
	}

	if StuboConfig.Debug == true {
		log.SetLevel(log.DebugLevel)
		log.Info("Starting server with debug mode initiated...")
	}
	// looking for option args when starting App
	// like ./lgc -port=":3000" would start on port 3000
	var port = flag.String("port", ":3000", "Server port")
	flag.Parse() // parse the flag

	// assign StuboURI
	StuboURI = StuboConfig.StuboProtocol + "://" + StuboConfig.StuboHost + ":" + StuboConfig.StuboPort

	log.WithFields(log.Fields{
		"StuboHost": StuboConfig.StuboHost,
		"StuboPort": StuboConfig.StuboPort,
		"StuboURI":  StuboURI,
		"ProxyPort": port,
	}).Info("LGC is starting")

	client := &Client{&http.Client{}}
	mux := getRouter(HandlerHTTPClient{*client})

	n := negroni.Classic()
	n.Use(negronilogrus.NewMiddleware())
	n.UseHandler(mux)
	n.Run(*port)
}
开发者ID:rusenask,项目名称:lgc,代码行数:52,代码来源:server.go


示例18: Initialize

func Initialize() {
	log.SetOutput(os.Stderr)
	log.SetLevel(log.WarnLevel)

	if boolVerbose {
		log.SetFormatter(&LogFormatter{})
		log.SetLevel(log.InfoLevel)
	}
	if boolDebug {
		log.SetFormatter(&log.TextFormatter{})
		log.SetLevel(log.DebugLevel)
	}
}
开发者ID:ChengTiesheng,项目名称:talk2docker,代码行数:13,代码来源:app.go


示例19: initLogging

func initLogging() {
	// level
	level, err := logrus.ParseLevel(viper.GetString("log-level"))
	if err != nil {
		logrus.WithError(err).Warn(`invalid log level. Defaulting to "info"`)
		level = logrus.InfoLevel
	}
	logrus.SetLevel(level)

	// format
	switch viper.GetString("log-format") {
	case "text":
		logrus.SetFormatter(new(logrus.TextFormatter))
	case "json":
		logrus.SetFormatter(new(logrus.JSONFormatter))
	default:
		logrus.SetFormatter(new(logrus.TextFormatter))
		logrus.WithField("format", viper.GetString("log-format")).Warn(`invalid log format. Defaulting to "text"`)
	}

	// output
	dest, err := url.Parse(viper.GetString("log-destination"))
	if err != nil {
		logrus.WithError(err).WithField("destination", viper.GetString("log-destination")).Error(`invalid log destination. Defaulting to "stdout:"`)
		dest.Scheme = "stdout"
	}

	switch dest.Scheme {
	case "stdout":
		// default, we don't need to do anything
	case "file":
		logrus.AddHook(lfshook.NewHook(lfshook.PathMap{
			logrus.DebugLevel: dest.Opaque,
			logrus.InfoLevel:  dest.Opaque,
			logrus.WarnLevel:  dest.Opaque,
			logrus.ErrorLevel: dest.Opaque,
			logrus.FatalLevel: dest.Opaque,
		}))
	case "journald":
		journalhook.Enable()
	case "syslog":
		hook, err := logrus_syslog.NewSyslogHook(dest.Fragment, dest.Host, syslog.LOG_DEBUG, dest.User.String())
		if err != nil {
			logrus.WithError(err).Error("could not configure syslog hook")
		} else {
			logrus.AddHook(hook)
		}
	default:
		logrus.WithField("destination", viper.GetString("log-destination")).Warn(`invalid log destination. Defaulting to "stdout:"`)
	}
}
开发者ID:asteris-llc,项目名称:vaultfs,代码行数:51,代码来源:utils.go


示例20: main

func main() {

	flag.BoolVar(&debug, "debug", false, "")
	flag.StringVar(&pathToConfig, "c", "", "")

	flag.Usage = func() {

		fmt.Println(usage)

		os.Exit(0)
	}

	flag.Parse()

	if log.IsTerminal() {

		log.SetFormatter(&log.TextFormatter{
			FullTimestamp:   true,
			TimestampFormat: "2006-01-02 15:04:05 MST",
		})

	} else {

		log.SetFormatter(&log.JSONFormatter{
			TimestampFormat: "2006-01-02 15:04:05 MST",
		})
	}

	config, err := common.ReadConfig(pathToConfig)

	if err != nil {

		log.Fatalf("Error reading configuration file: %v", err)
	}

	if debug {
		log.SetLevel(log.DebugLevel)
	} else {
		log.SetLevel(config.LogLevel())
	}

	app := app.New(config)

	if debug {

		app.SetDebugMode()
	}

	app.Run()
}
开发者ID:postgres-ci,项目名称:worker,代码行数:50,代码来源:worker.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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