slog: add missing calls to Handler.Enabled

Add an enabled check in handlerWriter, which is called to
send output from the log package through a handler.

Also add one to logDepthErr and remove it from logPC,
so that the check comes earlier.

Change-Id: Ia9f988093e2cd1551539470fc0c3733b3de8d7a3
Reviewed-on: https://go-review.googlesource.com/c/exp/+/459558
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Jonathan Amsterdam <jba@google.com>
Reviewed-by: Marko Kungla <marko.kungla@gmail.com>
Reviewed-by: Alan Donovan <adonovan@google.com>
diff --git a/slog/logger.go b/slog/logger.go
index d949a3d..cde76c6 100644
--- a/slog/logger.go
+++ b/slog/logger.go
@@ -45,6 +45,9 @@
 }
 
 func (w *handlerWriter) Write(buf []byte) (int, error) {
+	if !w.h.Enabled(LevelInfo) {
+		return 0, nil
+	}
 	var depth int
 	if w.flags&(log.Lshortfile|log.Llongfile) != 0 {
 		depth = 2
@@ -155,9 +158,6 @@
 }
 
 func (l *Logger) logPC(err error, pc uintptr, level Level, msg string, args ...any) {
-	if !l.Enabled(level) {
-		return
-	}
 	r := l.makeRecord(msg, level, pc)
 	r.setAttrsFromArgs(args)
 	if err != nil {
diff --git a/slog/logger_test.go b/slog/logger_test.go
index 5f40cc1..c574b00 100644
--- a/slog/logger_test.go
+++ b/slog/logger_test.go
@@ -108,6 +108,14 @@
 	log.Print("msg2")
 	checkLogOutput(t, slogbuf.String(), "time="+timeRE+` level=INFO msg=msg2`)
 
+	// The default log.Logger always outputs at Info level.
+	slogbuf.Reset()
+	SetDefault(New(HandlerOptions{Level: LevelWarn}.NewTextHandler(&slogbuf)))
+	log.Print("should not appear")
+	if got := slogbuf.String(); got != "" {
+		t.Errorf("got %q, want empty", got)
+	}
+
 	// Setting log's output again breaks the connection.
 	logbuf.Reset()
 	slogbuf.Reset()
@@ -119,6 +127,7 @@
 	if got := slogbuf.String(); got != "" {
 		t.Errorf("got %q, want empty", got)
 	}
+
 }
 
 type wrappingHandler struct {
diff --git a/slog/pc.go b/slog/pc.go
index cf2d771..52e04b3 100644
--- a/slog/pc.go
+++ b/slog/pc.go
@@ -45,6 +45,9 @@
 // with logic based on the Record's pc, and remove this function. See the
 // comment on TestConnections/wrap_default_handler.
 func (l *Logger) logDepthErr(err error, calldepth int, level Level, msg string, args ...any) {
+	if !l.Enabled(level) {
+		return
+	}
 	var pcs [1]uintptr
 	runtime.Callers(calldepth+2, pcs[:])
 	l.logPC(err, pcs[0], level, msg, args...)