当前位置: 首页>>代码示例>>Golang>>正文


Golang logrus.NewEntry函数代码示例

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


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

示例1: ServeHTTP

func (m *Logger) ServeHTTP(w http.ResponseWriter, r *http.Request, n http.HandlerFunc) {
	remoteAddr := r.RemoteAddr
	if realIP := r.Header.Get("X-Real-IP"); realIP != "" {
		remoteAddr = realIP
	}

	f := logrus.Fields{}
	f["request"] = r.URL.Path
	f["method"] = r.Method
	f["remote"] = remoteAddr
	logrus.NewEntry(m.Logger).WithFields(f).Debug("new request accepted")

	start := time.Now()
	n(w, r)

	status := w.(negroni.ResponseWriter).Status()

	f["status"] = status
	f["elapsed"] = time.Since(start)

	entry := logrus.NewEntry(m.Logger).WithFields(f)
	if status != 200 {
		entry.Warning("completed handling request, with errors")
		return
	}

	entry.Info("completed handling request")
}
开发者ID:mcuadros,项目名称:gop.kg,代码行数:28,代码来源:logger.go

示例2: logger

func (ctx *Context) logger(req *http.Request) *logrus.Entry {
	log := logrus.NewEntry(ctx.log)
	if reqID := requestID(req); reqID != "" {
		log = log.WithField("request_id", reqID)
	}
	return log
}
开发者ID:seanhess,项目名称:straitjacket,代码行数:7,代码来源:context.go

示例3: NewLogEntry

func (l *StructuredLogger) NewLogEntry(r *http.Request) middleware.LogEntry {
	entry := &StructuredLoggerEntry{logger: logrus.NewEntry(l.logger)}
	logFields := logrus.Fields{}

	logFields["ts"] = time.Now().UTC().Format(time.RFC1123)

	if reqID := middleware.GetReqID(r.Context()); reqID != "" {
		logFields["req_id"] = reqID
	}

	scheme := "http"
	if r.TLS != nil {
		scheme = "https"
	}
	logFields["http_scheme"] = scheme
	logFields["http_proto"] = r.Proto
	logFields["http_method"] = r.Method

	logFields["remote_addr"] = r.RemoteAddr
	logFields["user_agent"] = r.UserAgent()

	logFields["uri"] = fmt.Sprintf("%s://%s%s", scheme, r.Host, r.RequestURI)

	entry.logger = entry.logger.WithFields(logFields)

	entry.logger.Infoln("request started")

	return entry
}
开发者ID:pressly,项目名称:chi,代码行数:29,代码来源:main.go

示例4: TestFetchWishlist

func TestFetchWishlist(t *testing.T) {
	log := logrus.NewEntry(logrus.New())
	wishlister, _ := NewFakeWishlister([]byte{}, log)

	conf := WishlistConfig{
		Wishlisters:           []Wishlister{wishlister},
		ShowDefaultQualities:  []Quality{Quality480p, Quality1080p},
		MovieDefaultQualities: []Quality{Quality1080p, Quality720p},
	}

	wl := NewWishlist(conf, log)

	if err := wl.Fetch(); err != nil {
		t.Fatalf("Expected no error, got %q", err)
	}

	// Test movies
	movies := wl.Movies
	if !reflect.DeepEqual(movies, expectedWishedMoviesWithQualities) {
		t.Errorf("Expected %#v, got %#v", expectedWishedMovies, movies)
	}

	shows := wl.Shows
	if !reflect.DeepEqual(shows, expectedWishedShowsWithQualities) {
		t.Errorf("Expected %#v, got %#v", expectedWishedShows, shows)
	}
}
开发者ID:odwrtw,项目名称:polochon,代码行数:27,代码来源:wishilister_test.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: TestLogrusWithJsonFormatter

func TestLogrusWithJsonFormatter(t *testing.T) {
	p := &Person{
		Name:  "Bruce",
		Alias: "Batman",
		Hideout: &Hideout{
			Name:        "JLU Tower",
			DimensionId: 52,
		},
	}

	log.SetFormatter(newJsonFormatter())

	entry := log.NewEntry(log.StandardLogger())
	entry.Message = "the dark knight"
	entry.Data = log.Fields{"hero": p}
	s, _ := entry.String()

	if !strings.Contains(s, `"hero.name":"Bruce"`) {
		t.Fatalf(`missing "hero.name":"Bruce"`)
	}

	if !strings.Contains(s, `"hero.alias":"Batman"`) {
		t.Fatalf(`missing "hero.alias":"Batman"`)
	}

	if !strings.Contains(s, `"hero.hideout.name":"JLU Tower"`) {
		t.Fatalf(`missing "hero.hideout.name":"JLU Tower"`)
	}

	if !strings.Contains(s, `"hero.hideout.dimensionId":52`) {
		t.Fatalf(`missing "hero.hideout.dimensionId":52`)
	}
}
开发者ID:akutz,项目名称:golf,代码行数:33,代码来源:json_formatter_test.go

示例7: setUpRepo

// initialize a repo with keys, so they can be rotated
func setUpRepo(t *testing.T, tempBaseDir, gun string, ret notary.PassRetriever) (
	*httptest.Server, map[string]string) {

	// Set up server
	ctx := context.WithValue(
		context.Background(), "metaStore", storage.NewMemStorage())

	// Do not pass one of the const KeyAlgorithms here as the value! Passing a
	// string is in itself good test that we are handling it correctly as we
	// will be receiving a string from the configuration.
	ctx = context.WithValue(ctx, "keyAlgorithm", "ecdsa")

	// Eat the logs instead of spewing them out
	l := logrus.New()
	l.Out = bytes.NewBuffer(nil)
	ctx = ctxu.WithLogger(ctx, logrus.NewEntry(l))

	cryptoService := cryptoservice.NewCryptoService(trustmanager.NewKeyMemoryStore(ret))
	ts := httptest.NewServer(server.RootHandler(nil, ctx, cryptoService, nil, nil, nil))

	repo, err := client.NewNotaryRepository(
		tempBaseDir, gun, ts.URL, http.DefaultTransport, ret, trustpinning.TrustPinConfig{})
	require.NoError(t, err, "error creating repo: %s", err)

	rootPubKey, err := repo.CryptoService.Create("root", "", data.ECDSAKey)
	require.NoError(t, err, "error generating root key: %s", err)

	err = repo.Initialize(rootPubKey.ID())
	require.NoError(t, err)

	return ts, repo.CryptoService.ListAllKeys()
}
开发者ID:cyli,项目名称:notary,代码行数:33,代码来源:keys_test.go

示例8: LogRPCWithFields

// LogRPCWithFields will feed any request context into a logrus Entry.
func LogRPCWithFields(log *logrus.Logger, ctx context.Context) *logrus.Entry {
	md, ok := metadata.FromContext(ctx)
	if !ok {
		return logrus.NewEntry(log)
	}
	return log.WithFields(MetadataToFields(md))
}
开发者ID:pugong,项目名称:gizmo,代码行数:8,代码来源:rpc_server.go

示例9: TestSetupBolt

func TestSetupBolt(t *testing.T) {
	log := logrus.NewEntry(&logrus.Logger{})
	err := SetupBolt(path, log)
	if err != nil {
		t.Errorf("Failed to setup bolt: %s", err)
	}
	defer os.Remove(path)

	if err := DB.Close(); err != nil {
		t.Errorf("Failed to close bolt: %s", err)
	}

	// check if meta bucket exists
	db, err := bolt.Open(path, 0600, nil)
	if err != nil {
		t.Errorf("Failed to open bolt: %s", err)
	}

	db.View(func(tx *bolt.Tx) error {
		bkt := tx.Bucket([]byte(metabucket))
		if bkt == nil {
			t.Errorf("Meta bucket nof found")
		}
		return nil
	})

}
开发者ID:ymomoi,项目名称:vuls,代码行数:27,代码来源:bolt_test.go

示例10: Spawn

// Spawn initializes the HTTP component
func (httpsender *HTTPSender) Spawn(id int) utils.Composer {
	s := *httpsender
	s.id = id

	if httpsender.Config.Logger == nil {
		s.logger = logrus.NewEntry(logrus.New())
		s.logger.Logger.Out = ioutil.Discard
	} else {
		s.logger = httpsender.Config.Logger.WithFields(logrus.Fields{
			"worker": id,
		})
	}

	if httpsender.Debug {
		s.logger.Logger.Level = logrus.DebugLevel
	}

	s.logger.Debugf("Spawning worker")

	if govalidator.IsURL(s.URL) {
		s.Client = new(http.Client)

		if httpsender.Config.Insecure {
			s.Client.Transport = &http.Transport{
				TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
			}
		}
	} else {
		s.err = errors.New("Invalid URL")
	}

	return &s
}
开发者ID:redBorder,项目名称:rbforwarder,代码行数:34,代码来源:httpSender.go

示例11: getLogrusLogger

// GetLogrusLogger returns the logrus logger for the context. If one more keys
// are provided, they will be resolved on the context and included in the
// logger. Only use this function if specific logrus functionality is
// required.
func getLogrusLogger(ctx Context, keys ...interface{}) *logrus.Entry {
	var logger *logrus.Entry

	// Get a logger, if it is present.
	loggerInterface := ctx.Value("logger")
	if loggerInterface != nil {
		if lgr, ok := loggerInterface.(*logrus.Entry); ok {
			logger = lgr
		}
	}

	if logger == nil {
		// If no logger is found, just return the standard logger.
		logger = logrus.NewEntry(logrus.StandardLogger())
	}

	fields := logrus.Fields{}

	for _, key := range keys {
		v := ctx.Value(key)
		if v != nil {
			fields[fmt.Sprint(key)] = v
		}
	}

	return logger.WithFields(fields)
}
开发者ID:useidel,项目名称:notary,代码行数:31,代码来源:logger.go

示例12: dumpConfigToLog

func dumpConfigToLog() {
	l := log.NewEntry(log.StandardLogger())

	for k, v := range config.AllSettings() {
		l = l.WithField(k, v)
	}
	l.Debug("running with configuration")
}
开发者ID:kshlm,项目名称:glusterd2,代码行数:8,代码来源:config.go

示例13: TestWrite

func TestWrite(t *testing.T) {
	entry := logrus.NewEntry(logrus.New())
	entry.Message = "foobar"
	formatter := MachineFormatter{}
	bytes, err := formatter.Format(entry)
	assert.Nil(t, err)
	assert.Equal(t, string(bytes[:]), "foobar\n")
}
开发者ID:thbkrkr,项目名称:docker-machine-driver-ovh,代码行数:8,代码来源:machine_formatter_test.go

示例14: TestGetChangelogCache

func TestGetChangelogCache(t *testing.T) {
	const servername = "server1"
	pack := models.PackageInfo{
		Name:       "apt",
		Version:    "1.0.0",
		NewVersion: "1.0.1",
	}
	var meta = cache.Meta{
		Name: servername,
		Distro: config.Distro{
			Family:  "ubuntu",
			Release: "16.04",
		},
		Packs: []models.PackageInfo{pack},
	}

	const path = "/tmp/vuls-test-cache-11111111.db"
	log := logrus.NewEntry(&logrus.Logger{})
	if err := cache.SetupBolt(path, log); err != nil {
		t.Errorf("Failed to setup bolt: %s", err)
	}
	defer os.Remove(path)

	if err := cache.DB.EnsureBuckets(meta); err != nil {
		t.Errorf("Failed to ensure buckets: %s", err)
	}

	d := newDebian(config.ServerInfo{})
	actual := d.getChangelogCache(&meta, pack)
	if actual != "" {
		t.Errorf("Failed to get empty stirng from cache:")
	}

	clog := "changelog-text"
	if err := cache.DB.PutChangelog(servername, "apt", clog); err != nil {
		t.Errorf("Failed to put changelog: %s", err)
	}

	actual = d.getChangelogCache(&meta, pack)
	if actual != clog {
		t.Errorf("Failed to get changelog from cache: %s", actual)
	}

	// increment a version of the pack
	pack.NewVersion = "1.0.2"
	actual = d.getChangelogCache(&meta, pack)
	if actual != "" {
		t.Errorf("The changelog is not invalidated: %s", actual)
	}

	// change a name of the pack
	pack.Name = "bash"
	actual = d.getChangelogCache(&meta, pack)
	if actual != "" {
		t.Errorf("The changelog is not invalidated: %s", actual)
	}
}
开发者ID:ymomoi,项目名称:vuls,代码行数:57,代码来源:debian_test.go

示例15: New

// New creates a new logger according to horizon specifications.
func New() (result *logrus.Entry, m *Metrics) {
	m = NewMetrics()
	l := logrus.New()
	l.Level = logrus.WarnLevel
	l.Hooks.Add(m)

	result = logrus.NewEntry(l)
	return
}
开发者ID:raymens,项目名称:horizon,代码行数:10,代码来源:main.go


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