From 73bbf04abeee4e046ca4fc6f4f73596c7e88a5c1 Mon Sep 17 00:00:00 2001 From: Neale Pickett Date: Thu, 29 Jan 2015 17:57:37 +0000 Subject: [PATCH] Add logfile.go --- src/logfile/logfile.go | 87 +++++++++++++++++++ .../wirc.cgi.go => spongy.cgi/spongy.cgi.go} | 0 src/{wirc/wirc.go => spongy/spongy.go} | 0 3 files changed, 87 insertions(+) create mode 100644 src/logfile/logfile.go rename src/{wirc.cgi/wirc.cgi.go => spongy.cgi/spongy.cgi.go} (100%) rename src/{wirc/wirc.go => spongy/spongy.go} (100%) diff --git a/src/logfile/logfile.go b/src/logfile/logfile.go new file mode 100644 index 0000000..1a6e518 --- /dev/null +++ b/src/logfile/logfile.go @@ -0,0 +1,87 @@ +package logfile + +import ( + "fmt" + "os" + "time" +) + +type Logfile struct { + file *os.File + name string + nlines int + maxlines int +} + +func NewLogfile(maxlines int) (*Logfile) { + return &Logfile{nil, "", 0, maxlines} +} + +func (lf *Logfile) Close() { + if lf.file != nil { + lf.writeln("EXIT") + lf.file.Close() + } +} + +func (lf *Logfile) writeln(s string) error { + _, err := fmt.Fprintf(lf.file, "%d %s\n", time.Now().Unix(), s) + if err == nil { + lf.nlines += 1 + } + return err +} + +func (lf *Logfile) rotate() error { + fn := fmt.Sprintf("%s.log", time.Now().UTC().Format(time.RFC3339)) + newf, err := os.OpenFile(fn, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0666) + if err != nil { + return err + } + + if lf.file == nil { + // Set lf.file just so we can write out NEXTLOG. + // If this fails, that's okay + lf.file, _ = os.OpenFile("current", os.O_WRONLY|os.O_APPEND, 0666) + } + + if lf.file != nil { + // Note location of new log + logmsg := fmt.Sprintf(". NEXTLOG %s", fn) + lf.writeln(logmsg) + + // All done with the current log + lf.file.Close() + } + + // Point to new log file + lf.file = newf + + // Record symlink to new log + os.Remove("current") + os.Symlink(fn, "current") + + logmsg := fmt.Sprintf(". PREVLOG %s", lf.name) + lf.writeln(logmsg) + + lf.name = fn + + return nil +} + +func (lf *Logfile) Log(s string) error { + if lf.file == nil { + lf.rotate() + } + + err := lf.writeln(s) + if err == nil { + return err + } + + if lf.nlines >= lf.maxlines { + return lf.rotate() + } + + return nil +} diff --git a/src/wirc.cgi/wirc.cgi.go b/src/spongy.cgi/spongy.cgi.go similarity index 100% rename from src/wirc.cgi/wirc.cgi.go rename to src/spongy.cgi/spongy.cgi.go diff --git a/src/wirc/wirc.go b/src/spongy/spongy.go similarity index 100% rename from src/wirc/wirc.go rename to src/spongy/spongy.go