示例#1
0
func ExampleWithValue(ctx context.Context, n1, n2 int) error {
	if err := doSomethingWith(n1, n2); err != nil {
		return slog.Error(ctx, "doSomethingWith failed",
			slog.WithValue("n1", n1),
			slog.WithValue("n2", n2))
	}

	// ... more processing and then ...

	return nil
}
示例#2
0
func ExampleOption(ctx context.Context, n1, n2 int) error {
	if err := doSomethingWith(n1, n2); err != nil {
		return slog.Error(ctx, "cannot doSomething",
			slog.WithValue("n1", n1),
			slog.WithValue("n2", n2),
			slog.WithError(err))
	}

	// .. more processing and then ...

	return nil
}
示例#3
0
func ExampleNewWriter(ctx context.Context) {
	// Creates a HTTP server whose error log will write to the
	// default slog.Logger. Any panics that are recovered will
	// have the details logged via slog.
	httpServer := &http.Server{
		Addr:     ":8080",
		ErrorLog: log.New(slog.NewWriter(ctx), "http", 0),
	}

	slog.Info(ctx, "web server started", slog.WithValue("addr", httpServer.Addr))
	if err := httpServer.ListenAndServe(); err != nil {
		slog.Error(ctx, "web server failed", slog.WithError(err))
	}

	// 2009-11-10T12:34:56.789 info msg="web server started" addr=:8080
	// 2009-11-10T12:35:57:987 error msg="http: panic serving 123.1:2.3:36145 runtime error: invalid memory address or nil pointer dereference"
}