Skip to content

Commit

Permalink
Add example of log rotation
Browse files Browse the repository at this point in the history
  • Loading branch information
sevlyar committed Jun 4, 2017
1 parent da3ad60 commit bad4990
Show file tree
Hide file tree
Showing 3 changed files with 174 additions and 0 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,6 @@ func main() {

![](img/idea.png)

## Examples

* [Log rotation](examples/cmd/gd-log-rotation/)
61 changes: 61 additions & 0 deletions examples/cmd/gd-log-rotation/log_file.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package main

import (
"os"
"sync"
"time"
)

type LogFile struct {
mu sync.Mutex
name string
file *os.File
}

// NewLogFile creates a new LogFile. The file is optional - it will be created if needed.
func NewLogFile(name string, file *os.File) (*LogFile, error) {
rw := &LogFile{
file: file,
name: name,
}
if file == nil {
if err := rw.Rotate(); err != nil {
return nil, err
}
}
return rw, nil
}

func (l *LogFile) Write(b []byte) (n int, err error) {
l.mu.Lock()
n, err = l.file.Write(b)
l.mu.Unlock()
return
}

// Rotate renames old log file, creates new one, switches log and closes the old file.
func (l *LogFile) Rotate() error {
// rename dest file if it already exists.
if _, err := os.Stat(l.name); err == nil {
name := l.name + "." + time.Now().Format(time.RFC3339)
if err = os.Rename(l.name, name); err != nil {
return err
}
}
// create new file.
file, err := os.Create(l.name)
if err != nil {
return err
}
// switch dest file safely.
l.mu.Lock()
file, l.file = l.file, file
l.mu.Unlock()
// close old file if open.
if file != nil {
if err := file.Close(); err != nil {
return err
}
}
return nil
}
110 changes: 110 additions & 0 deletions examples/cmd/gd-log-rotation/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package main

import (
"flag"
"github.com/sevlyar/go-daemon"
"log"
"os"
"syscall"
"time"
)

var (
signal = flag.String("s", "", `send signal to the daemon
stop — shutdown`)
)

const logFileName = "log"

func main() {
flag.Parse()
daemon.AddCommand(daemon.StringFlag(signal, "stop"), syscall.SIGTERM, termHandler)

cntxt := &daemon.Context{
PidFileName: "pid",
PidFilePerm: 0644,
LogFileName: logFileName,
LogFilePerm: 0640,
WorkDir: "./",
Umask: 027,
Args: []string{"[go-daemon sample]"},
}

if len(daemon.ActiveFlags()) > 0 {
d, err := cntxt.Search()
if err != nil {
log.Fatalln("Unable send signal to the daemon:", err)
}
daemon.SendCommands(d)
return
}

d, err := cntxt.Reborn()
if err != nil {
log.Fatalln(err)
}
if d != nil {
return
}
defer cntxt.Release()

log.Println("- - - - - - - - - - - - - - -")
log.Println("daemon started")

setupLog()

go worker()

err = daemon.ServeSignals()
if err != nil {
log.Println("Error:", err)
}
log.Println("daemon terminated")
}

func setupLog() {
lf, err := NewLogFile(logFileName, os.Stderr)
if err != nil {
log.Fatal("Unable to create log file: ", err)
}
log.SetOutput(lf)
// rotate log every 30 seconds.
rotateLogSignal := time.Tick(30 * time.Second)
go func() {
for {
<-rotateLogSignal
if err := lf.Rotate(); err != nil {
log.Fatal("Unable to rotate log: ", err)
}
}
}()
}

var (
stop = make(chan struct{})
done = make(chan struct{})
)

func worker() {
LOOP:
for {
// spam to log every one second (as payload).
log.Print("+ ", time.Now().Unix())
time.Sleep(time.Second)
select {
case <-stop:
break LOOP
default:
}
}
done <- struct{}{}
}

func termHandler(sig os.Signal) error {
log.Println("terminating...")
stop <- struct{}{}
if sig == syscall.SIGQUIT {
<-done
}
return daemon.ErrStop
}

0 comments on commit bad4990

Please sign in to comment.