changlin19 / reopen

freopen functionality for golang's io.Writers

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Build Status Go Report Card GoDoc license

Makes a standard os.File a "reopenable writer" and allows SIGHUP signals to reopen log files, as needed by logrotated. This is inspired by the C/Posix freopen

The simple version reopen.NewFileWriter does unbuffered writing. A call to .Reopen closes the existing file handle, and then re-opens it using the original filename.

The more advanced version reopen.NewBufferedFileWriter buffers input and flushes when the internal buffer is full (with care) or if 30 seconds has elapsed.

There is also reopen.Stderr and reopen.Stdout which implements the reopen.Reopener interface (and does nothing on a reopen call).

reopen.Discard wraps ioutil.Discard

Samples are in example1 and example2. The run.sh scripts are a dumb test where the file is rotated underneath the server, and nothing is lost. This is not the most robust test but gives you an idea of how it works.

Here's some sample code.

package main

/* Simple logrotate logger
 */
import (
       "fmt"
       "log"
       "net/http"
       "os"
       "os/signal"
       "syscall"

       "github.com/client9/reopen"
)

func main() {
        // setup logger to write to our new *reopenable* log file

        f, err := reopen.NewFileWriter("/tmp/example.log")
        if err != nil {
           log.Fatalf("Unable to set output log: %s", err)
        }
        log.SetOutput(f)

        // Handle SIGHUP
        //
        // channel is number of signals needed to catch  (more or less)
        // we only are working with one here, SIGHUP
        sighup := make(chan os.Signal, 1)
        signal.Notify(sighup, syscall.SIGHUP)
        go func() {
           for {
               <-sighup
              fmt.Println("Got a sighup")
              f.Reopen()
            }
         }()

        // dumb http server that just prints and logs the path
        http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
            log.Printf("%s", r.URL.Path)
            fmt.Fprintf(w, "%s\n", r.URL.Path)
        })
        log.Fatal(http.ListenAndServe("127.0.0.1:8123", nil))
}

About

freopen functionality for golang's io.Writers

License:MIT License


Languages

Language:Go 84.0%Language:Shell 8.3%Language:Makefile 7.6%