feat(log): timestamp on archive only

This commit is contained in:
Mikaël Cluseau 2018-06-20 07:23:19 +11:00
parent dc622fb466
commit 3b512e6105
2 changed files with 16 additions and 17 deletions

View File

@ -18,9 +18,7 @@ func compress(path string) {
defer in.Close() defer in.Close()
outPath := filepath.Join(filepath.Dir(path), "archives", filepath.Base(path)+".xz") outPath := filepath.Join(filepath.Dir(path), filepath.Base(path)+".xz")
os.MkdirAll(filepath.Dir(outPath), 0700)
out, err := os.Create(outPath) out, err := os.Create(outPath)
if err != nil { if err != nil {

View File

@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"io" "io"
"os" "os"
"path/filepath"
"sync" "sync"
"time" "time"
@ -34,7 +35,7 @@ type Log struct {
console io.Writer console io.Writer
pending []Entry pending []Entry
out *os.File out *os.File
outPath string outTS string
} }
func Get(name string) *Log { func Get(name string) *Log {
@ -207,21 +208,26 @@ func (l *Log) Write(b []byte) (n int, err error) {
} }
func (l *Log) writeEntry(e Entry) (err error) { func (l *Log) writeEntry(e Entry) (err error) {
path := fmt.Sprintf("/var/log/%s.%s.log", ts := e.Time.Truncate(time.Hour).Format(time.RFC3339)
l.name, e.Time.Truncate(time.Hour).Format(time.RFC3339))
currentPath := fmt.Sprintf("/var/log/%s.log", l.name) path := fmt.Sprintf("/var/log/%s.log", l.name)
if l.outPath != path { if l.outTS != ts {
if l.out != nil { if l.out != nil {
if err := l.out.Close(); err != nil { if err := l.out.Close(); err != nil {
fmt.Fprintf(os.Stderr, "log %s: failed to close output: %v\n", l.name, err) fmt.Fprintf(os.Stderr, "log %s: failed to close output: %v\n", l.name, err)
} }
os.Remove(currentPath) archPath := fmt.Sprintf("/var/log/archives/%s.%s.log", l.name, l.outTS)
go compress(l.outPath)
os.MkdirAll(filepath.Dir(archPath), 0700)
if err := os.Rename(path, archPath); err != nil {
fmt.Fprintf(os.Stderr, "log %s: failed to achive: %v", l.name, err)
}
go compress(archPath)
} }
l.out = nil l.out = nil
l.outPath = "" l.outTS = ""
} }
if l.out == nil { if l.out == nil {
@ -230,12 +236,7 @@ func (l *Log) writeEntry(e Entry) (err error) {
return return
} }
l.outPath = path l.outTS = ts
os.Remove(currentPath)
if err := os.Symlink(path, currentPath); err != nil {
fmt.Fprintf(os.Stderr, "failed to symlink %s.log: %v\n", l.name, err)
}
} }
_, err = e.WriteTo(l.out) _, err = e.WriteTo(l.out)