8 . "github.com/tendermint/tmlibs/common"
13 // Create/Append to ./autofile_test
14 af, err := OpenAutoFile("autofile_test")
20 // During this time, the file may be moved e.g. by logRotate.
21 for i := 0; i < 60; i++ {
22 af.Write([]byte(Fmt("LOOP(%v)", i)))
23 time.Sleep(time.Second)
33 const autoFileOpenDuration = 1000 * time.Millisecond
35 // Automatically closes and re-opens file for writing.
36 // This is useful for using a log file with the logrotate tool.
37 type AutoFile struct {
45 func OpenAutoFile(path string) (af *AutoFile, err error) {
47 ID: RandStr(12) + ":" + path,
49 ticker: time.NewTicker(autoFileOpenDuration),
51 if err = af.openFile(); err != nil {
55 sighupWatchers.addAutoFile(af)
59 func (af *AutoFile) Close() error {
62 sighupWatchers.removeAutoFile(af)
66 func (af *AutoFile) processTicks() {
68 _, ok := <-af.ticker.C
76 func (af *AutoFile) closeFile() (err error) {
88 func (af *AutoFile) Write(b []byte) (n int, err error) {
93 if err = af.openFile(); err != nil {
98 n, err = af.file.Write(b)
102 func (af *AutoFile) Sync() error {
104 defer af.mtx.Unlock()
107 if err := af.openFile(); err != nil {
111 return af.file.Sync()
114 func (af *AutoFile) openFile() error {
115 file, err := os.OpenFile(af.Path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
123 func (af *AutoFile) Size() (int64, error) {
125 defer af.mtx.Unlock()
130 if err == os.ErrNotExist {
137 stat, err := af.file.Stat()
141 return stat.Size(), nil