@@ -27,6 +27,7 @@ import (
27
27
"os"
28
28
"path/filepath"
29
29
"strings"
30
+ "sync"
30
31
"syscall"
31
32
"time"
32
33
@@ -49,6 +50,9 @@ type PidFile struct {
49
50
CustomName string `json:"name"`
50
51
51
52
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
52
56
}
53
57
54
58
func New (dir string , args []string ) * PidFile {
@@ -257,16 +261,34 @@ func (p *PidFile) LogReader() (io.ReadCloser, error) {
257
261
return r , nil
258
262
}
259
263
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).
260
272
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
+
266
287
if err != nil {
267
288
return nil , err
268
289
}
269
- return w , nil
290
+
291
+ return p .lw , err
270
292
}
271
293
272
294
func (p * PidFile ) Binary () string {
0 commit comments