Skip to content

Commit a8dc8da

Browse files
committed
fix(log): Panic redirection to logs
Firstly, make sure the file exists before we try to get the handle to it. Secondly, duplicate the file handle and pass it to SetStdHandle.
1 parent 7847552 commit a8dc8da

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

internal/bootstrap/bootstrap.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ func (f *App) Run(args []string) error {
180180
}
181181

182182
log.Infof("bootstrapping with pid %d. Version: %s", os.Getpid(), version.Get())
183-
log.Infof("rendering config flags... %s", cfg.Print())
183+
log.Infof("configuration options: %s", cfg.Print())
184184

185185
// build the filter from the CLI argument. If we got
186186
// a valid expression the filter is attached to the

pkg/util/log/logger.go

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -122,16 +122,30 @@ func InitFromConfig(c Config, filename string) error {
122122
return nil
123123
}
124124

125+
// redirectStderrToFile redirects the standard output stream to a log file.
126+
// Helpful to capture panics and send them to the file.
125127
func redirectStderrToFile(file string) error {
126-
f, err := os.OpenFile(file, os.O_WRONLY|os.O_SYNC|os.O_APPEND, 0644)
128+
f, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_SYNC|os.O_APPEND, 0644)
127129
if err != nil {
128130
return fmt.Errorf("unable to open %s for stderr redirection: %v", file, err)
129131
}
130132
defer f.Close()
131-
err = windows.SetStdHandle(windows.STD_ERROR_HANDLE, windows.Handle(f.Fd()))
133+
134+
fd, err := dupFD(f.Fd())
135+
if err != nil {
136+
return fmt.Errorf("failed to duplicate file handle: %v", err)
137+
}
138+
139+
err = windows.SetStdHandle(windows.STD_ERROR_HANDLE, fd)
132140
if err != nil {
133141
return fmt.Errorf("failed to redirect stderr to file: %v", err)
134142
}
135-
os.Stderr = f
143+
136144
return nil
137145
}
146+
147+
func dupFD(fd uintptr) (windows.Handle, error) {
148+
proc := windows.CurrentProcess()
149+
var h windows.Handle
150+
return h, windows.DuplicateHandle(proc, windows.Handle(fd), proc, &h, 0, true, windows.DUPLICATE_SAME_ACCESS)
151+
}

0 commit comments

Comments
 (0)