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

Golang log.NewLogfmtLogger函数代码示例

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

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



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

示例1: TestSyncLoggerConcurrency

func TestSyncLoggerConcurrency(t *testing.T) {
	var w io.Writer
	w = &bytes.Buffer{}
	logger := log.NewLogfmtLogger(w)
	logger = log.NewSyncLogger(logger)
	testConcurrency(t, logger, 10000)
}
开发者ID:basvanbeek,项目名称:kit,代码行数:7,代码来源:sync_test.go


示例2: main

func main() {

	// setup a logger
	logger = log.NewLogfmtLogger(os.Stderr)
	logger = log.NewContext(logger).With("svc", "sensor").With("caller", log.DefaultCaller)

	// setup rethinkdb session
	session := getSession()

	// build the context
	ctx := context.Background()

	// new service
	svc := NewSensorService(session)

	// wrap it in the logging middleware
	svc = loggingMiddleware(logger)(svc)

	// bind the service to HTTP with the context
	// with it's matching encoder/decoder
	recordHandler := httptransport.NewServer(
		ctx,
		makeRecordEndpoint(svc),
		decodeRecordRequest,
		encodeResponse,
	)

	// assign an endpoint route
	http.Handle("/sensor/record", recordHandler)

	// bind the listener
	logger.Log("msg", "HTTP", "addr", ":5000")
	logger.Log("err", http.ListenAndServe(":5000", nil))
}
开发者ID:wolfeidau,项目名称:sensord,代码行数:34,代码来源:main.go


示例3: Example

func Example() {

	// make a normal, go-kit Logger
	logger := kitlog.NewLogfmtLogger(os.Stdout)
	// wrap it with serial awesome sauce
	logger = NewSerialLogger(logger, 50)

	var wg sync.WaitGroup
	wg.Add(threadCount)

	// spawn threadCount goroutines to log concurrently
	for i := 0; i < threadCount; i++ {
		go func() {
			defer wg.Done()

			slice := KVs()
			// log my data printCount times
			for j := 0; j < printCount; j++ {
				logger.Log(slice...)
			}
		}()
	}

	wg.Wait()

	logger.(SerialLogger).Flush()
}
开发者ID:seastar-io,项目名称:log,代码行数:27,代码来源:example_test.go


示例4: main

func main() {
	// `package log` domain
	var logger kitlog.Logger
	logger = kitlog.NewLogfmtLogger(os.Stderr)
	logger = kitlog.NewContext(logger).With("ts", kitlog.DefaultTimestampUTC)
	stdlog.SetOutput(kitlog.NewStdlibAdapter(logger)) // redirect stdlib logging to us
	stdlog.SetFlags(0)                                // flags are handled in our logger

	// read configuration from environment
	c, err := config.LoadConfiguration()
	if err != nil {
		logger.Log("fatal", err.Error())
		return
	}

	// Mechanical stuff
	rand.Seed(time.Now().UnixNano())
	root := context.Background()
	errc := make(chan error)

	go func() {
		errc <- interrupt()
	}()

	// Start bindings
	binding.StartApplicationSQSConsumer(logger, root, errc, c)
	binding.StartHealthCheckHTTPListener(logger, root, errc, c)

	logger.Log("fatal", <-errc)
}
开发者ID:skidder,项目名称:streammarker-writer,代码行数:30,代码来源:writer.go


示例5: TestContext

func TestContext(t *testing.T) {
	t.Parallel()
	buf := &bytes.Buffer{}
	logger := log.NewLogfmtLogger(buf)

	kvs := []interface{}{"a", 123}
	lc := log.NewContext(logger).With(kvs...)
	kvs[1] = 0 // With should copy its key values

	lc = lc.With("b", "c") // With should stack
	if err := lc.Log("msg", "message"); err != nil {
		t.Fatal(err)
	}
	if want, have := "a=123 b=c msg=message\n", buf.String(); want != have {
		t.Errorf("\nwant: %shave: %s", want, have)
	}

	buf.Reset()
	lc = lc.WithPrefix("p", "first")
	if err := lc.Log("msg", "message"); err != nil {
		t.Fatal(err)
	}
	if want, have := "p=first a=123 b=c msg=message\n", buf.String(); want != have {
		t.Errorf("\nwant: %shave: %s", want, have)
	}
}
开发者ID:ryancox,项目名称:kit,代码行数:26,代码来源:log_test.go


示例6: Example_context

func Example_context() {
	logger := log.NewLogfmtLogger(os.Stdout)

	type Task struct {
		ID  int
		Cmd string
	}

	taskHelper := func(cmd string, logger log.Logger) {
		// execute(cmd)
		logger.Log("cmd", cmd, "dur", 42*time.Millisecond)
	}

	RunTask := func(task Task, logger log.Logger) {
		logger = log.NewContext(logger).With("taskID", task.ID)
		logger.Log("event", "starting task")

		taskHelper(task.Cmd, logger)

		logger.Log("event", "task complete")
	}

	RunTask(Task{ID: 1, Cmd: "echo Hello, world!"}, logger)

	// Output:
	// taskID=1 event="starting task"
	// taskID=1 cmd="echo Hello, world!" dur=42ms
	// taskID=1 event="task complete"
}
开发者ID:basvanbeek,项目名称:kit,代码行数:29,代码来源:example_test.go


示例7: TestLogfmtLogger

func TestLogfmtLogger(t *testing.T) {
	t.Parallel()
	buf := &bytes.Buffer{}
	logger := log.NewLogfmtLogger(buf)

	if err := logger.Log("hello", "world"); err != nil {
		t.Fatal(err)
	}
	if want, have := "hello=world\n", buf.String(); want != have {
		t.Errorf("want %#v, have %#v", want, have)
	}

	buf.Reset()
	if err := logger.Log("a", 1, "err", errors.New("error")); err != nil {
		t.Fatal(err)
	}
	if want, have := "a=1 err=error\n", buf.String(); want != have {
		t.Errorf("want %#v, have %#v", want, have)
	}

	buf.Reset()
	if err := logger.Log("std_map", map[int]int{1: 2}, "my_map", mymap{0: 0}); err != nil {
		t.Fatal(err)
	}
	if want, have := "std_map=\""+logfmt.ErrUnsupportedValueType.Error()+"\" my_map=special_behavior\n", buf.String(); want != have {
		t.Errorf("want %#v, have %#v", want, have)
	}
}
开发者ID:basvanbeek,项目名称:kit,代码行数:28,代码来源:logfmt_logger_test.go


示例8: TestDefaultLevels

func TestDefaultLevels(t *testing.T) {
	buf := bytes.Buffer{}
	logger := levels.New(log.NewLogfmtLogger(&buf))

	logger.Debug().Log("msg", "résumé") // of course you'd want to do this
	if want, have := "level=debug msg=résumé\n", buf.String(); want != have {
		t.Errorf("want %#v, have %#v", want, have)
	}

	buf.Reset()
	logger.Info().Log("msg", "Åhus")
	if want, have := "level=info msg=Åhus\n", buf.String(); want != have {
		t.Errorf("want %#v, have %#v", want, have)
	}

	buf.Reset()
	logger.Error().Log("msg", "© violation")
	if want, have := "level=error msg=\"© violation\"\n", buf.String(); want != have {
		t.Errorf("want %#v, have %#v", want, have)
	}

	buf.Reset()
	logger.Crit().Log("msg", "	")
	if want, have := "level=crit msg=\"\\t\"\n", buf.String(); want != have {
		t.Errorf("want %#v, have %#v", want, have)
	}
}
开发者ID:cnicolov,项目名称:kit,代码行数:27,代码来源:levels_test.go


示例9: main

func main() {
	logger = log.NewLogfmtLogger(os.Stderr)
	logger = log.NewContext(logger).With("ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller)
	logger.Log("msg", "Starting bikefinder")
	var err error

	db_url := os.Getenv("DATABASE_URL")
	DB, err = crud.Connect("mysql", db_url)

	if err != nil {
		logger.Log("msg", "Failed to connect to db at "+db_url, "error", err)
		panic(err)
	}

	err = DB.CreateTables(DockingStationStatus{})
	if err != nil {
		logger.Log("msg", "Failed to create db table", "error", err)
		panic(err)
	}

	http.HandleFunc("/schemes", getSchemes)
	http.HandleFunc("/stations", getStationsInside)
	http.HandleFunc("/bikes-near", getBikesNear)
	http.HandleFunc("/freedocks-near", getFreeDocksNear)
	http.HandleFunc("/map", getMap)
	http.HandleFunc("/ingest", ingest)
	http.Handle("/", http.FileServer(http.Dir("./static")))
	bind := fmt.Sprintf("%s:%s", os.Getenv("OPENSHIFT_GO_IP"), os.Getenv("OPENSHIFT_GO_PORT"))
	logger.Log("msg", "Attempting to listen on "+bind)
	err = http.ListenAndServe(bind, nil)
	if err != nil {
		logger.Log("msg", "Failed to listen", "error", err)
		panic(err)
	}
}
开发者ID:andrewl,项目名称:bikefinder,代码行数:35,代码来源:main.go


示例10: main

func main() {
	logger := log.NewLogfmtLogger(os.Stdout)

	ctx := context.Background()

	c := &countService{}

	var svc endpoint.Endpoint
	svc = makeAddEndpoint(c)

	limit := ratelimit.NewBucket(2*time.Second, 1)
	svc = kitratelimit.NewTokenBucketLimiter(limit)(svc)

	requestCount := expvar.NewCounter("request.count")
	svc = metricsMiddleware(requestCount)(svc)
	svc = loggingMiddlware(logger)(svc)

	addHandler := httptransport.NewServer(
		ctx,
		svc,
		decodeAddRequest,
		encodeResponse,
		httptransport.ServerBefore(beforeIDExtractor, beforePATHExtractor),
	)

	http.Handle("/add", addHandler)

	port := os.Getenv("PORT")
	logger.Log("listening on", port)
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		logger.Log("listen.error", err)
	}
}
开发者ID:heroku-examples,项目名称:go-kit-ex1,代码行数:33,代码来源:main.go


示例11: TestStringifyLogger

func TestStringifyLogger(t *testing.T) {
	buf := &bytes.Buffer{}
	logger := log.NewLogfmtLogger(buf)
	logger = kithlp.StringifyLogger{logger}

	if err := logger.Log("hello", "world"); err != nil {
		t.Fatal(err)
	}
	if want, have := "hello=world\n", buf.String(); want != have {
		t.Errorf("want %#v, have %#v", want, have)
	}

	buf.Reset()
	if err := logger.Log("a", 1, "err", errors.New("error")); err != nil {
		t.Fatal(err)
	}
	if want, have := "a=1 err=error\n", buf.String(); want != have {
		t.Errorf("want %#v, have %#v", want, have)
	}

	buf.Reset()
	if err := logger.Log("std_map", map[int]int{1: 2}, "my_map", mymap{0: 0}); err != nil {
		t.Fatal(err)
	}
	if want, have := "std_map=map[1:2] my_map=special_behavior\n", buf.String(); want != have {
		t.Errorf("want %#v, have %#v", want, have)
	}
}
开发者ID:rdterner,项目名称:go-1,代码行数:28,代码来源:stringify_logger_test.go


示例12: main

func main() {
	logger := log.NewLogfmtLogger(os.Stderr)
	logger = log.NewContext(logger).With("ts", log.DefaultTimestampUTC)

	err := godotenv.Load()
	if err != nil {
		logger.Log("level", "fatal", "err", err)
	}

	config := &Config{
		Addr: os.Getenv("ADDR"),
		DSN:  os.Getenv("DSN"),
	}

	db, err := gorm.Open("postgres", config.DSN)
	if err != nil {
		panic(err)
	}

	app := cli.NewApp()

	app.Commands = []cli.Command{{
		Name:   "serve",
		Action: serve(logger, config, db),
	}}

	if err := app.Run(os.Args); err != nil {
		logger.Log("level", "fatal", "err", err)
	}

}
开发者ID:MetalMatze,项目名称:Krautreporter-API,代码行数:31,代码来源:api.go


示例13: TestCatalogueServiceTags

func TestCatalogueServiceTags(t *testing.T) {
	logger = log.NewLogfmtLogger(os.Stderr)
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Fatalf("an error '%s' was not expected when opening stub database connection", err)
	}
	defer db.Close()
	sqlxDB := sqlx.NewDb(db, "sqlmock")

	var cols []string = []string{"name"}

	mock.ExpectQuery("SELECT name FROM tag").WillReturnRows(sqlmock.NewRows(cols).
		AddRow(tags[0]).
		AddRow(tags[1]).
		AddRow(tags[2]))

	s := NewCatalogueService(sqlxDB, logger)

	have, err := s.Tags()
	if err != nil {
		t.Errorf("Tags(): %v", err)
	}
	if !reflect.DeepEqual(tags, have) {
		t.Errorf("Tags(): want %v, have %v", tags, have)
	}
}
开发者ID:xwh123807,项目名称:microapps,代码行数:26,代码来源:service_test.go


示例14: TestTrackTrackCargo

func TestTrackTrackCargo(t *testing.T) {
	var (
		cargos         = repository.NewInMemcargo()
		handlingEvents = repository.NewInMemHandlingEvent()
		service        = NewService(cargos, handlingEvents)
	)

	c := cargo.New("TEST", cargo.RouteSpecification{
		Origin:          "SESTO",
		Destination:     "FIHEL",
		ArrivalDeadline: time.Date(2005, 12, 4, 0, 0, 0, 0, time.UTC),
	})
	cargos.Store(c)

	ctx := context.Background()

	logger := log.NewLogfmtLogger(ioutil.Discard)

	h := MakeHandler(ctx, service, logger)

	req, _ := http.NewRequest("GET", "http://example.com/tracking/v1/cargos/TEST", nil)
	rec := httptest.NewRecorder()

	h.ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Errorf("rec.Code = %d; want = %d", rec.Code, http.StatusOK)
	}

	if content := rec.Header().Get("Content-Type"); content != "application/json; charset=utf-8" {
		t.Errorf("Content-Type = %q; want = %q", content, "application/json; charset=utf-8")
	}

	var response trackCargoResponse
	if err := json.NewDecoder(rec.Body).Decode(&response); err != nil {
		t.Error(err)
	}

	if response.Err != nil {
		t.Errorf("response.Err = %q", response.Err)
	}

	var eta time.Time

	want := Cargo{
		TrackingID:           "TEST",
		Origin:               "SESTO",
		Destination:          "FIHEL",
		ArrivalDeadline:      time.Date(2005, 12, 4, 0, 0, 0, 0, time.UTC),
		ETA:                  eta.In(time.UTC),
		StatusText:           "Not received",
		NextExpectedActivity: "There are currently no expected activities for this cargo.",
		Events:               nil,
	}

	if !reflect.DeepEqual(want, *response.Cargo) {
		t.Errorf("response.Cargo = %#v; want = %#v", response.Cargo, want)
	}
}
开发者ID:xiejianzheng,项目名称:goddd,代码行数:59,代码来源:transport_test.go


示例15: main

func main() {
	var svc stringsvc.StringService = StringService{}
	l := log.NewLogfmtLogger(os.Stderr)
	svc = logging.Middleware(l, svc)(svc)

	trans.ServersForEndpoints(svc)
	http.ListenAndServe(":9000", nil)
}
开发者ID:Ayiga,项目名称:go-kit-middlewarer,代码行数:8,代码来源:main.go


示例16: StructuredLogger

// StructuredLogger provide a minimal structured Logger implementation with the provided io.Writer
// Uses go-kit log to write in Logfmt
// See https://github.com/go-kit/kit/tree/master/log
func StructuredLogger(w io.Writer) Logger {
	l := gokitlog.NewLogfmtLogger(w)
	var logger LoggerFunc
	logger = func(c Call) {
		l.Log("msg", "calling api", "origin_id", c.OriginID, "duration", c.TimeTaken, "method", c.CalleeID, "request", fmt.Sprintf("%#v", c.Req), "request_body", c.ReqBody, "response", fmt.Sprintf("%#v", c.Res), "response_body", c.ResBody, "error", c.Err)
	}
	return logger
}
开发者ID:homemade,项目名称:justin,代码行数:11,代码来源:requests.go


示例17: main

func main() {
	var (
		listen = flag.String("listen", ":8080", "HTTP listen address")
		proxy  = flag.String("proxy", "", "Optional comma-separated list of URLs to proxy uppercase requests")
	)
	flag.Parse()

	var logger log.Logger
	logger = log.NewLogfmtLogger(os.Stderr)
	logger = log.NewContext(logger).With("listen", *listen).With("caller", log.DefaultCaller)

	ctx := context.Background()

	fieldKeys := []string{"method", "error"}
	requestCount := kitprometheus.NewCounter(stdprometheus.CounterOpts{
		Namespace: "my_group",
		Subsystem: "string_service",
		Name:      "request_count",
		Help:      "Number of requests received.",
	}, fieldKeys)
	requestLatency := metrics.NewTimeHistogram(time.Microsecond, kitprometheus.NewSummary(stdprometheus.SummaryOpts{
		Namespace: "my_group",
		Subsystem: "string_service",
		Name:      "request_latency_microseconds",
		Help:      "Total duration of requests in microseconds.",
	}, fieldKeys))
	countResult := kitprometheus.NewSummary(stdprometheus.SummaryOpts{
		Namespace: "my_group",
		Subsystem: "string_service",
		Name:      "count_result",
		Help:      "The result of each count method.",
	}, []string{})

	var svc StringService
	svc = stringService{}
	svc = proxyingMiddleware(*proxy, ctx, logger)(svc)
	svc = loggingMiddleware(logger)(svc)
	svc = instrumentingMiddleware(requestCount, requestLatency, countResult)(svc)

	uppercaseHandler := httptransport.NewServer(
		ctx,
		makeUppercaseEndpoint(svc),
		decodeUppercaseRequest,
		encodeResponse,
	)
	countHandler := httptransport.NewServer(
		ctx,
		makeCountEndpoint(svc),
		decodeCountRequest,
		encodeResponse,
	)

	http.Handle("/uppercase", uppercaseHandler)
	http.Handle("/count", countHandler)
	http.Handle("/metrics", stdprometheus.Handler())
	logger.Log("msg", "HTTP", "addr", *listen)
	logger.Log("err", http.ListenAndServe(*listen, nil))
}
开发者ID:cnicolov,项目名称:kit,代码行数:58,代码来源:main.go


示例18: New

// New returns a new Weavebox object
func New() *Weavebox {
	return &Weavebox{
		router:          httprouter.New(),
		Output:          os.Stderr,
		ErrorHandler:    defaultErrorHandler,
		EnableAccessLog: false,
		logger:          kitlog.NewLogfmtLogger(os.Stderr),
	}
}
开发者ID:twanies,项目名称:weavebox,代码行数:10,代码来源:weavebox.go


示例19: ExampleLevels

func ExampleLevels() {
	logger := levels.New(log.NewLogfmtLogger(os.Stdout))
	logger.Debug("msg", "hello")
	logger.With("context", "foo").Warn("err", "error")

	// Output:
	// level=debug msg=hello
	// level=warn context=foo err=error
}
开发者ID:apsanz,项目名称:kit,代码行数:9,代码来源:levels_test.go


示例20: main

func main() {
	ctx := context.Background()

	logger := log.NewLogfmtLogger(os.Stderr)

	fieldKeys := []string{"method", "error"}
	requestCount := kitprometheus.NewCounter(stdprometheus.CounterOpts{
		Namespace: "my_group",
		Subsystem: "string_service",
		Name:      "request_count",
		Help:      "Number of requests received.",
	}, fieldKeys)
	requestLatency := metrics.NewTimeHistogram(time.Microsecond, kitprometheus.NewSummary(stdprometheus.SummaryOpts{
		Namespace: "my_group",
		Subsystem: "string_service",
		Name:      "request_latency_microseconds",
		Help:      "Total duration of requests in microseconds.",
	}, fieldKeys))
	countResult := kitprometheus.NewSummary(stdprometheus.SummaryOpts{
		Namespace: "my_group",
		Subsystem: "string_service",
		Name:      "count_result",
		Help:      "The result of each count method.",
	}, []string{}) // no fields here

	var svc StringService
	svc = stringService{}
	svc = loggingMiddleware{logger, svc}
	svc = instrumentingMiddleware{requestCount, requestLatency, countResult, svc}

	var uppercase endpoint.Endpoint
	uppercase = makeUppercaseEndpoint(svc)

	var count endpoint.Endpoint
	count = makeCountEndpoint(svc)

	uppercaseHandler := httptransport.Server{
		Context:            ctx,
		Endpoint:           uppercase,
		DecodeRequestFunc:  decodeUppercaseRequest,
		EncodeResponseFunc: encodeResponse,
	}

	countHandler := httptransport.Server{
		Context:            ctx,
		Endpoint:           count,
		DecodeRequestFunc:  decodeCountRequest,
		EncodeResponseFunc: encodeResponse,
	}

	http.Handle("/uppercase", uppercaseHandler)
	http.Handle("/count", countHandler)
	http.Handle("/metrics", stdprometheus.Handler())

	stdlog.Fatal(http.ListenAndServe(":8080", nil))
}
开发者ID:hatchan,项目名称:gokit-sample,代码行数:56,代码来源:main.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang log.NewNopLogger函数代码示例发布时间:2022-05-23
下一篇:
Golang log.NewJSONLogger函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap