Skip to content

Commit edcf2f8

Browse files
authored
Merge pull request #626 from tucksaun/fix/no-runner-logs
do not truncate log files on each LogWriter calls
2 parents 3d44daa + 606fd41 commit edcf2f8

File tree

1 file changed

+28
-6
lines changed

1 file changed

+28
-6
lines changed

local/pid/pidfile.go

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import (
2727
"os"
2828
"path/filepath"
2929
"strings"
30+
"sync"
3031
"syscall"
3132
"time"
3233

@@ -49,6 +50,9 @@ type PidFile struct {
4950
CustomName string `json:"name"`
5051

5152
path string
53+
54+
lwInit sync.Once // used to ensure that the log writer is only created once
55+
lw io.WriteCloser // log writer, used to write logs to the log file
5256
}
5357

5458
func New(dir string, args []string) *PidFile {
@@ -257,16 +261,34 @@ func (p *PidFile) LogReader() (io.ReadCloser, error) {
257261
return r, nil
258262
}
259263

264+
// LogWriter returns a writer to write logs to the log file. It creates the log
265+
// file if it does not exist, and truncates it if it does. It is safe to call
266+
// this method multiple times, it will only create the log file once per process
267+
// lifetime: it is useful to have a single truncation (and thus a clean log
268+
// file) at the beginning of the process management but not to truncate the log
269+
// file when the process is restarted.
270+
// Please note this method might not return a writer even if the error is nil
271+
// (the error is returned only for the first call).
260272
func (p *PidFile) LogWriter() (io.WriteCloser, error) {
261-
logFile := p.LogFile()
262-
if err := os.MkdirAll(filepath.Dir(logFile), 0755); err != nil {
263-
return nil, err
264-
}
265-
w, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
273+
var err error
274+
275+
p.lwInit.Do(func() {
276+
logFile := p.LogFile()
277+
if err = errors.WithStack(os.MkdirAll(filepath.Dir(logFile), 0755)); err != nil {
278+
return
279+
}
280+
p.lw, err = os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
281+
if err != nil {
282+
err = errors.WithStack(err)
283+
return
284+
}
285+
})
286+
266287
if err != nil {
267288
return nil, err
268289
}
269-
return w, nil
290+
291+
return p.lw, err
270292
}
271293

272294
func (p *PidFile) Binary() string {

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy