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

Golang logrus.New函数代码示例

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

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



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

示例1: Test_changefeed

func Test_changefeed(t *testing.T) {
	s := storage.NewMemStorage()

	tests := []changefeedTest{
		{
			name: "Empty Store",
			args: changefeedArgs{
				logger:    logrus.New(),
				store:     s,
				imageName: "",
				changeID:  "0",
				pageSize:  notary.DefaultPageSize,
			},
			want:    []byte("{\"count\":0,\"records\":null}"),
			wantErr: false,
		},
		{
			name: "Bad ChangeID",
			args: changefeedArgs{
				logger:    logrus.New(),
				store:     s,
				imageName: "",
				changeID:  "not_a_number",
				pageSize:  notary.DefaultPageSize,
			},
			want:    nil,
			wantErr: true,
		},
	}
	runChangefeedTests(t, tests)

}
开发者ID:jfrazelle,项目名称:notary,代码行数:32,代码来源:changefeed_test.go


示例2: TestClient

func TestClient(t *testing.T) {
	assert.Panics(t, func() {
		NewAPIMock(true, logrus.New(), "panic!")
	}, "It must panic if wrong type")

	api := NewAPIMock(true, logrus.New(), "json")
	assert.IsType(t, api, new(APIMock), "It must instance an APIMock struct")
	assert.Equal(t, api.CORSEnabled, true, "Cors must be TRUE")
	assert.Equal(t, api.Log, logrus.New(), "Logger must be set correctly")
	assert.Equal(t, api.Type, "json", "Type must be 'json'")
}
开发者ID:fernandezvara,项目名称:apimock,代码行数:11,代码来源:apimock_test.go


示例3: NewOptionsFromConfig

// NewOptionsFromConfig extracts bits from a config to make an agent options object
func NewOptionsFromConfig(cfg *config.Config) *Options {
	log := logrus.New()
	opts := &Options{
		Env: cfg.Env,
		Log: logrus.New(),
	}

	if cfg.LogFormat == "json" {
		log.Formatter = &logrus.JSONFormatter{}
	}

	opts.Log = Logger(log)
	return opts
}
开发者ID:hamfist,项目名称:go-newrelic,代码行数:15,代码来源:options.go


示例4: TestRecoverMiddleware

func TestRecoverMiddleware(t *testing.T) {
	req := &protocol.Request{
		Method: "foobar",
		Params: protocol.Params{},
		Header: header.Header{},
	}
	rw := &dummy.ResponseWriter{
		HeaderValues: header.Header{},
	}

	buff := bytes.NewBufferString("")
	logger := log.New()
	logger.Out = buff

	handler := Chain(panicHandler, NewRecover(logger, true, 8*1024))

	handler.Handle(rw, req)

	loglines := buff.String()

	expectedLog := regexp.MustCompile(`error="Booom"`)
	if expectedLog.FindString(loglines) != "" {
		t.Errorf("didn't find expected log line in %s", loglines)
	}
}
开发者ID:mamachanko,项目名称:go-nano,代码行数:25,代码来源:recover_test.go


示例5: main

func main() {
	log := logrus.New()
	cli.VersionPrinter = func(c *cli.Context) {
		fmt.Printf("%s v=%s d=%s\n", c.App.Name, c.App.Version, GeneratedString)
	}

	app := cli.NewApp()
	app.Name = "artifacts-service"
	app.Version = VersionString
	app.Commands = []cli.Command{
		{
			Name:      "serve",
			ShortName: "s",
			Usage:     "run the HTTP thing",
			Action: func(_ *cli.Context) {
				server.Main(log)
			},
		},
		{
			Name:      "migrate",
			ShortName: "m",
			Usage:     "run database migrations",
			Action: func(_ *cli.Context) {
				server.MigratorMain(log)
			},
		},
	}

	app.Run(os.Args)
}
开发者ID:hamfist,项目名称:artifacts-service,代码行数:30,代码来源:artifacts_service.go


示例6: main

func main() {
	r := gin.New()

	// Add a ginrus middleware, which:
	//   - Logs all requests, like a combined access and error log.
	//   - Logs to stdout.
	//   - RFC3339 with UTC time format.
	r.Use(ginrus.Ginrus(logrus.StandardLogger(), time.RFC3339, true))

	// Add similar middleware, but:
	//   - Only logs requests with errors, like an error log.
	//   - Logs to stderr instead of stdout.
	//   - Local time zone instead of UTC.
	logger := logrus.New()
	logger.Level = logrus.ErrorLevel
	logger.Out = os.Stderr
	r.Use(ginrus.Ginrus(logger, time.RFC3339, false))

	// Example ping request.
	r.GET("/ping", func(c *gin.Context) {
		c.String(200, "pong "+fmt.Sprint(time.Now().Unix()))
	})

	// Listen and Server in 0.0.0.0:8080
	r.Run(":8080")
}
开发者ID:doubledutch,项目名称:dd-vote,代码行数:26,代码来源:example.go


示例7: main

func main() {
	log := logrus.New()
	hook, err := logrus_influxdb.NewInfluxDB(nil)
	if err == nil {
		log.Hooks.Add(hook)
	}
}
开发者ID:Abramovic,项目名称:logrus_influxdb,代码行数:7,代码来源:main.go


示例8: Instance

func Instance() *log.Logger {
	if logger == nil {
		logger = log.New()
	}

	return logger
}
开发者ID:ch3lo,项目名称:crane,代码行数:7,代码来源:logger.go


示例9: Fire

func (h *TeeHook) Fire(entry *logrus.Entry) error {
	logger := logrus.New()
	logger.Out = h.W
	switch entry.Level {
	case logrus.PanicLevel:
		logger.WithFields(entry.Data).Panic(entry.Message)
		break
	case logrus.FatalLevel:
		logger.WithFields(entry.Data).Fatal(entry.Message)
		break
	case logrus.ErrorLevel:
		logger.WithFields(entry.Data).Error(entry.Message)
		break
	case logrus.WarnLevel:
		logger.WithFields(entry.Data).Warnf(entry.Message)
		break
	case logrus.InfoLevel:
		logger.WithFields(entry.Data).Info(entry.Message)
		break
	case logrus.DebugLevel:
		logger.WithFields(entry.Data).Info(entry.Message)
		break
	}
	return nil
}
开发者ID:layer-x,项目名称:layerx-commons,代码行数:25,代码来源:hooks.go


示例10: Run

func (svc *service) Run() (string, error) {
	logger := logrus.New()
	err := setupSyslog(logger)
	if err != nil {
		return "Could not create syslog", err
	}

	// load configuration file
	config, err := config.LoadFromFile(svc.args["<config-file>"].(string))
	if err != nil {
		logger.WithError(err).Error("Failed to open configuration file")
		return "Failed to open configuration file", err
	}

	w, err := worker.New(config, logger)
	if err != nil {
		logger.WithError(err).Error("Could not create worker")
		return "Could not create worker", err
	}

	sigTerm := make(chan os.Signal, 1)
	signal.Notify(sigTerm, os.Interrupt, os.Kill, syscall.SIGTERM)
	go func() {
		<-sigTerm
		w.Stop()
	}()
	w.Start()
	return "Worker successfully started", nil
}
开发者ID:taskcluster,项目名称:taskcluster-worker,代码行数:29,代码来源:service.go


示例11: main

func main() {
	log := logrus.New()
	log.Formatter = new(logrus.JSONFormatter)

	for {
		log.WithFields(logrus.Fields{
			"animal": "walrus",
			"size":   "10",
		}).Print("A group of walrus emerges from the ocean")

		log.WithFields(logrus.Fields{
			"omg":    true,
			"number": 122,
		}).Warn("The group's number increased tremendously!")

		log.WithFields(logrus.Fields{
			"animal": "walrus",
			"size":   "10",
		}).Print("A giant walrus appears!")

		log.WithFields(logrus.Fields{
			"animal": "walrus",
			"size":   "9",
		}).Print("Tremendously sized cow enters the ocean.")

		log.WithFields(logrus.Fields{
			"omg":    true,
			"number": 100,
		}).Fatal("The ice breaks!")
	}
}
开发者ID:shaunstanislaus,项目名称:logrus,代码行数:31,代码来源:text.go


示例12: New

func New(concurrentRequests int, hosts []string, startUrls []string) *Crawler {
	c := &Crawler{
		ConcurrentRequests: concurrentRequests,
		AllowCrawlPatterns: make([]*regexp.Regexp, 0),

		Logger: logrus.New(),

		Client: &http.Client{},

		itemQueue:   make([]*CrawlItem, 0),
		crawledUrls: make(map[string]bool),
		pendingUrls: make(map[string]bool),

		resultChannel: make(chan *CrawlItem),
	}

	for _, host := range hosts {
		re := regexp.MustCompile("https?\\://" + host + "*")
		c.AllowCrawlPatterns = append(c.AllowCrawlPatterns, re)
	}

	for _, url := range startUrls {
		c.itemQueue = append(c.itemQueue, &CrawlItem{
			Url: url,
		})
	}

	return c
}
开发者ID:app-kit,项目名称:go-appkit,代码行数:29,代码来源:crawler.go


示例13: main

func main() {
	var log = logrus.New()
	app := cli.NewApp()
	app.Name = "Geopardy"
	app.Usage = "Import and query Jeopardy questions"
	app.Action = func(c *cli.Context) {
		log.Out = os.Stderr
		log.WithFields(logrus.Fields{
			"args": c.Args(),
		}).Info("Called with args")
	}

	app.Commands = []cli.Command{
		{
			Name:  "import",
			Usage: "Import Jeopardy questions from the web to the database",
			Action: func(c *cli.Context) {
				err := imp.RunImport(c.Args())
				if err != nil {
					log.Error(err)
				}
			},
		},
	}

	app.Run(os.Args)
}
开发者ID:russmatney,项目名称:go-jeopardy,代码行数:27,代码来源:main.go


示例14: newRedisNotify

func newRedisNotify(accountID string) (*logrus.Logger, error) {
	rNotify := serverConfig.GetRedisNotifyByID(accountID)

	// Dial redis.
	rPool, err := dialRedis(rNotify)
	if err != nil {
		return nil, err
	}

	rrConn := redisConn{
		Pool:   rPool,
		params: rNotify,
	}

	redisLog := logrus.New()

	redisLog.Out = ioutil.Discard

	// Set default JSON formatter.
	redisLog.Formatter = new(logrus.JSONFormatter)

	redisLog.Hooks.Add(rrConn)

	// Success, redis enabled.
	return redisLog, nil
}
开发者ID:hackintoshrao,项目名称:minio,代码行数:26,代码来源:notify-redis.go


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


示例16: init

func init() {

	logger := logrus.New()
	logger.Level = logrus.InfoLevel

	Main = logger
}
开发者ID:TanUkkii007,项目名称:ecs-formation,代码行数:7,代码来源:logger.go


示例17: TestLogEntryWritten

// Tests that writing to a tempfile log works.
// Matches the 'msg' of the output and deletes the tempfile.
func TestLogEntryWritten(t *testing.T) {
	log := logrus.New()
	// The colors were messing with the regexp so I turned them off.
	log.Formatter = &logrus.TextFormatter{DisableColors: true}
	tmpfile, err := ioutil.TempFile("", "test_lfshook")
	if err != nil {
		t.Errorf("Unable to generate logfile due to err: %s", err)
	}
	fname := tmpfile.Name()
	defer func() {
		tmpfile.Close()
		os.Remove(fname)
	}()
	hook := NewHook(PathMap{
		logrus.InfoLevel: fname,
	})
	log.Hooks.Add(hook)

	log.Info(expectedMsg)

	if contents, err := ioutil.ReadAll(tmpfile); err != nil {
		t.Errorf("Error while reading from tmpfile: %s", err)
	} else if matched, err := regexp.Match("msg=\""+expectedMsg+"\"", contents); err != nil || !matched {
		t.Errorf("Message read (%s) doesnt match message written (%s) for file: %s", contents, expectedMsg, fname)
	}
}
开发者ID:marconi,项目名称:lfshook,代码行数:28,代码来源:lfshook_test.go


示例18: NewWithArgs

// NewWithArgs returns a new CLI using the specified arguments.
func NewWithArgs(ctx apitypes.Context, a ...string) *CLI {
	s := "REX-Ray:\n" +
		"  A guest-based storage introspection tool that enables local\n" +
		"  visibility and management from cloud and storage platforms."

	c := &CLI{
		l:      log.New(),
		ctx:    ctx,
		config: util.NewConfig(ctx),
	}

	c.c = &cobra.Command{
		Use:              "rexray",
		Short:            s,
		PersistentPreRun: c.preRun,
		Run: func(cmd *cobra.Command, args []string) {
			cmd.Usage()
		},
	}

	c.c.SetArgs(a)

	for _, f := range initCmdFuncs {
		f(c)
	}

	c.initUsageTemplates()

	return c
}
开发者ID:akutz,项目名称:rexray,代码行数:31,代码来源:cli.go


示例19: getPanicLogger

func getPanicLogger() *logrus.Logger {
	log := logrus.New()
	if os.Getenv("DEBUG") != "" && os.Getenv("ARTIFACTS_DEBUG") != "" {
		log.Level = logrus.DebugLevel
	}
	return log
}
开发者ID:hamfist,项目名称:artifacts-service,代码行数:7,代码来源:server_test.go


示例20: Run

// Run the application, start http and scp server.
func Run(appConfig Config) {
	config = appConfig

	// Connect to DB
	db, err := lib.Connect()
	if err != nil {
		fmt.Printf("Failed to connect to db")
		return
	}

	// Logging
	log := logrus.New()
	log.Level = logrus.DebugLevel
	log.Out = os.Stdout
	log.Formatter = &logrus.TextFormatter{}

	// Websockets
	ws := ws.NewServer()

	// Shared dependencies between all controller
	deps := dependencies.Dependencies{
		Fs:     afero.NewOsFs(),
		Logger: log,
		DB:     db,
		WS:     ws,
	}

	ws.Dependencies = &deps
	go ws.Start()

	// // Start SCP
	// scp := scp.Server{}
	// scp.DB = deps.DB
	// scp.Logger = deps.Logger
	// scp.CertPath = "certs/scp.rsa"
	// scp.BindAddr = config.SCPBindAddr
	// go scp.ListenAndServe()

	if config.Secure {
		c := autocert.DirCache("certs")
		m := autocert.Manager{
			Cache:      c,
			Prompt:     autocert.AcceptTOS,
			HostPolicy: autocert.HostWhitelist("x.zqz.ca"),
		}

		s := &http.Server{
			Addr:      config.HTTPBindAddr,
			TLSConfig: &tls.Config{GetCertificate: m.GetCertificate},
		}

		deps.Info("Listening for HTTP1.1 Connections", "addr", ":3001")
		deps.Info("Listening for HTTP2 Connections", "addr", config.HTTPBindAddr)
		go http.ListenAndServe(":3001", secureRedirect())
		s.ListenAndServeTLS("", "")
	} else {
		deps.Info("Listening for HTTP1.1 Connections", "addr", config.HTTPBindAddr)
		http.ListenAndServe(config.HTTPBindAddr, Routes(deps))
	}
}
开发者ID:zqzca,项目名称:back,代码行数:61,代码来源:app.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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