Skip to content

Commit 29f324a

Browse files
committed
log: console may be nil
1 parent fafa4f7 commit 29f324a

2 files changed

Lines changed: 29 additions & 5 deletions

File tree

intra/log/log.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
package log
3333

3434
import (
35+
"context"
3536
"errors"
3637
"fmt"
3738
)
@@ -76,9 +77,12 @@ func SetConsoleLevel(level LogLevel) {
7677
}
7778

7879
// SetConsole sets external console to redirect log output to.
79-
func SetConsole(c Console) {
80+
func SetConsole(consoleCtx context.Context, c Console) {
8081
Glogger.SetConsole(c)
8182

83+
context.AfterFunc(consoleCtx, func() {
84+
Glogger.SetConsole(nil) // reset console to nil
85+
})
8286
}
8387

8488
func Of(tag string, l LogFn2) LogFn {

intra/log/logger.go

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import (
3636
"fmt"
3737
golog "log"
3838
"os"
39+
"reflect"
3940
"runtime"
4041
"strings"
4142
"sync"
@@ -84,7 +85,10 @@ type simpleLogger struct {
8485

8586
type atom[T any] atomic.Value
8687

87-
func (a *atom[T]) get() T {
88+
func (a *atom[T]) get() (zz T) {
89+
if a == nil {
90+
return
91+
}
8892
aa := (*atomic.Value)(a)
8993
return aa.Load().(T)
9094
}
@@ -262,7 +266,7 @@ func (l *simpleLogger) SetConsoleLevel(n LogLevel) {
262266
func (l *simpleLogger) SetConsole(c Console) {
263267
l.clearStCounts()
264268

265-
l.c.set(c)
269+
l.c.set(c) // c may point to nil impl
266270
}
267271

268272
func (l *simpleLogger) clearStCounts() {
@@ -289,7 +293,7 @@ func (l *simpleLogger) consoleDispatcher() {
289293
continue
290294
}
291295
load := (len(l.cmsgC) / cap(l.cmsgC) * 100) // load percentage
292-
if c := l.c.get(); c != nil { // look for l.c on every msg
296+
if c := l.c.get(); c != nil && !IsNil(c) { // look for l.c on every msg
293297
switch m.t {
294298
case NONE:
295299
// drop
@@ -390,7 +394,7 @@ func (l *simpleLogger) emitStack(at int, msgs ...string) {
390394
}
391395
if !sendtoconsole {
392396
l.err(at+nextframe, msg)
393-
} else if c != nil {
397+
} else if c != nil && !IsNil(c) {
394398
// c.Stack() on the same go routine, since
395399
// the caller (ex: core.Recover) may exit
396400
// immediately once simpleLogger.Stack() returns
@@ -664,3 +668,19 @@ top:
664668
}
665669
return uint16(v) > tt
666670
}
671+
672+
// Cannot import pkg core here.
673+
// from: intra/core/typ.go:IsNil
674+
func IsNil(x any) bool {
675+
// from: stackoverflow.com/a/76595928
676+
if x == nil {
677+
return true
678+
}
679+
v := reflect.ValueOf(x)
680+
k := v.Kind()
681+
switch k {
682+
case reflect.Pointer, reflect.UnsafePointer, reflect.Interface, reflect.Chan, reflect.Func, reflect.Map, reflect.Slice:
683+
return v.IsNil()
684+
}
685+
return false
686+
}

0 commit comments

Comments
 (0)