town/external/lockingwriter/lockingwriter.go

56 lines
981 B
Go
Raw Normal View History

2023-11-01 02:44:22 +00:00
package lockingwriter
import (
"os"
"time"
"github.com/gofrs/flock"
)
// for now this package defines a writer for use with log.New(). It it intended to be used from the external ssh applications. This logger uses a file lock to allow all the various ssh applications to log to the same file.
type LockingWriter struct {
path string
}
2023-11-01 03:25:26 +00:00
const (
fp = "/town/var/log/external.log"
lp = "/town/var/log/log.lock"
)
2023-11-01 02:44:22 +00:00
2023-11-01 03:25:26 +00:00
func New() *LockingWriter {
f, err := os.OpenFile(fp, os.O_EXCL|os.O_CREATE|os.O_WRONLY, 0660)
2023-11-01 02:44:22 +00:00
if err != nil {
panic(err)
}
defer f.Close()
return &LockingWriter{
path: fp,
}
}
func (l *LockingWriter) Write(p []byte) (n int, err error) {
2023-11-01 03:25:26 +00:00
fl := flock.New(lp)
2023-11-01 02:44:22 +00:00
var locked bool
for !locked {
locked, err = fl.TryLock()
if err != nil {
return
}
time.Sleep(time.Second)
}
2023-11-01 03:25:26 +00:00
2023-11-01 02:44:22 +00:00
var f *os.File
f, err = os.OpenFile(l.path, os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
return
}
defer f.Close()
defer fl.Unlock()
return f.Write(p)
}