Commit b643a816 authored by Frank Denis's avatar Frank Denis

Add automatic log files rotation

Fixes #172
parent 97156c3a
......@@ -168,9 +168,15 @@
]
revision = "dd2ff4accc098aceecb86b36eaa7829b2a17b1c9"
[[projects]]
name = "gopkg.in/natefinch/lumberjack.v2"
packages = ["."]
revision = "a96e63847dc3c67d17befa69c303767e2f84e54f"
version = "v2.1"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "e5ab398cf5b03e4f180453c2386951fa2fa56652e64628eb38d763adf7ec596a"
inputs-digest = "32f9b1bb4dd9f1ca13e9daedf85fc6cc9f3a97a023171a32ac7a2144ba9c1956"
solver-name = "gps-cdcl"
solver-version = 1
......@@ -22,6 +22,10 @@
branch = "master"
name = "github.com/dchest/safefile"
[[constraint]]
branch = "master"
name = "github.com/facebookgo/pidfile"
[[constraint]]
branch = "master"
name = "github.com/hashicorp/go-immutable-radix"
......@@ -59,5 +63,5 @@
name = "golang.org/x/crypto"
[[constraint]]
branch = "master"
name = "github.com/facebookgo/pidfile"
name = "gopkg.in/natefinch/lumberjack.v2"
version = "2.1.0"
......@@ -52,6 +52,9 @@ type Config struct {
FallbackResolver string `toml:"fallback_resolver"`
IgnoreSystemDNS bool `toml:"ignore_system_dns"`
AllWeeklyRanges map[string]WeeklyRangesStr `toml:"schedules"`
LogMaxSize int `toml:"log_files_max_size"`
LogMaxAge int `toml:"log_files_max_age"`
LogMaxBackups int `toml:"log_files_max_backups"`
}
func newConfig() Config {
......@@ -75,6 +78,9 @@ func newConfig() Config {
MaxClients: 250,
FallbackResolver: DefaultFallbackResolver,
IgnoreSystemDNS: false,
LogMaxSize: 10,
LogMaxAge: 7,
LogMaxBackups: 1,
}
}
......@@ -169,6 +175,9 @@ func ConfigLoad(proxy *Proxy, svcFlag *string) error {
} else if config.LogFile != nil {
dlog.UseLogFile(*config.LogFile)
}
proxy.logMaxSize = config.LogMaxSize
proxy.logMaxAge = config.LogMaxAge
proxy.logMaxBackups = config.LogMaxBackups
proxy.xTransport.fallbackResolver = config.FallbackResolver
if len(config.FallbackResolver) > 0 {
proxy.xTransport.ignoreSystemDNS = config.IgnoreSystemDNS
......
......@@ -5,22 +5,20 @@ import (
"fmt"
"io/ioutil"
"net"
"os"
"strings"
"sync"
"time"
"unicode"
"github.com/hashicorp/go-immutable-radix"
"github.com/jedisct1/dlog"
"github.com/miekg/dns"
"gopkg.in/natefinch/lumberjack.v2"
)
type PluginBlockIP struct {
sync.Mutex
blockedPrefixes *iradix.Tree
blockedIPs map[string]interface{}
outFd *os.File
logger *lumberjack.Logger
format string
}
......@@ -75,13 +73,7 @@ func (plugin *PluginBlockIP) Init(proxy *Proxy) error {
if len(proxy.blockIPLogFile) == 0 {
return nil
}
plugin.Lock()
defer plugin.Unlock()
outFd, err := os.OpenFile(proxy.blockIPLogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
return err
}
plugin.outFd = outFd
plugin.logger = &lumberjack.Logger{LocalTime: true, MaxSize: proxy.logMaxSize, MaxAge: proxy.logMaxAge, MaxBackups: proxy.logMaxBackups, Filename: proxy.blockIPLogFile, Compress: true}
plugin.format = proxy.blockIPFormat
return nil
......@@ -126,7 +118,7 @@ func (plugin *PluginBlockIP) Eval(pluginsState *PluginsState, msg *dns.Msg) erro
}
if reject {
pluginsState.action = PluginsActionReject
if plugin.outFd != nil {
if plugin.logger != nil {
questions := msg.Question
if len(questions) != 1 {
return nil
......@@ -153,12 +145,10 @@ func (plugin *PluginBlockIP) Eval(pluginsState *PluginsState, msg *dns.Msg) erro
} else {
dlog.Fatalf("Unexpected log format: [%s]", plugin.format)
}
plugin.Lock()
if plugin.outFd == nil {
if plugin.logger == nil {
return errors.New("Log file not initialized")
}
plugin.outFd.WriteString(line)
defer plugin.Unlock()
plugin.logger.Write([]byte(line))
}
}
return nil
......
......@@ -5,17 +5,16 @@ import (
"fmt"
"io/ioutil"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"unicode"
"github.com/hashicorp/go-immutable-radix"
"github.com/jedisct1/dlog"
"github.com/miekg/dns"
lumberjack "gopkg.in/natefinch/lumberjack.v2"
)
type PluginBlockType int
......@@ -29,14 +28,13 @@ const (
)
type PluginBlockName struct {
sync.Mutex
blockedPrefixes *iradix.Tree
blockedSuffixes *iradix.Tree
allWeeklyRanges *map[string]WeeklyRanges
weeklyRangesIndirect map[string]*WeeklyRanges
blockedSubstrings []string
blockedPatterns []string
outFd *os.File
logger *lumberjack.Logger
format string
}
......@@ -157,13 +155,7 @@ func (plugin *PluginBlockName) Init(proxy *Proxy) error {
if len(proxy.blockNameLogFile) == 0 {
return nil
}
plugin.Lock()
defer plugin.Unlock()
outFd, err := os.OpenFile(proxy.blockNameLogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
return err
}
plugin.outFd = outFd
plugin.logger = &lumberjack.Logger{LocalTime: true, MaxSize: proxy.logMaxSize, MaxAge: proxy.logMaxAge, MaxBackups: proxy.logMaxBackups, Filename: proxy.blockNameLogFile, Compress: true}
plugin.format = proxy.blockNameFormat
return nil
......@@ -236,7 +228,7 @@ func (plugin *PluginBlockName) Eval(pluginsState *PluginsState, msg *dns.Msg) er
}
if reject {
pluginsState.action = PluginsActionReject
if plugin.outFd != nil {
if plugin.logger != nil {
var clientIPStr string
if pluginsState.clientProto == "udp" {
clientIPStr = (*pluginsState.clientAddr).(*net.UDPAddr).IP.String()
......@@ -255,12 +247,10 @@ func (plugin *PluginBlockName) Eval(pluginsState *PluginsState, msg *dns.Msg) er
} else {
dlog.Fatalf("Unexpected log format: [%s]", plugin.format)
}
plugin.Lock()
if plugin.outFd == nil {
if plugin.logger == nil {
return errors.New("Log file not initialized")
}
plugin.outFd.WriteString(line)
defer plugin.Unlock()
plugin.logger.Write([]byte(line))
}
}
return nil
......
......@@ -4,18 +4,16 @@ import (
"errors"
"fmt"
"net"
"os"
"sync"
"time"
"github.com/jedisct1/dlog"
"github.com/miekg/dns"
lumberjack "gopkg.in/natefinch/lumberjack.v2"
)
type PluginNxLog struct {
sync.Mutex
outFd *os.File
format string
logger *lumberjack.Logger
format string
}
func (plugin *PluginNxLog) Name() string {
......@@ -27,13 +25,7 @@ func (plugin *PluginNxLog) Description() string {
}
func (plugin *PluginNxLog) Init(proxy *Proxy) error {
plugin.Lock()
defer plugin.Unlock()
outFd, err := os.OpenFile(proxy.nxLogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
return err
}
plugin.outFd = outFd
plugin.logger = &lumberjack.Logger{LocalTime: true, MaxSize: proxy.logMaxSize, MaxAge: proxy.logMaxAge, MaxBackups: proxy.logMaxBackups, Filename: proxy.nxLogFile, Compress: true}
plugin.format = proxy.nxLogFormat
return nil
......@@ -81,12 +73,10 @@ func (plugin *PluginNxLog) Eval(pluginsState *PluginsState, msg *dns.Msg) error
} else {
dlog.Fatalf("Unexpected log format: [%s]", plugin.format)
}
plugin.Lock()
if plugin.outFd == nil {
if plugin.logger == nil {
return errors.New("Log file not initialized")
}
plugin.outFd.WriteString(line)
defer plugin.Unlock()
plugin.logger.Write([]byte(line))
return nil
}
......@@ -4,18 +4,16 @@ import (
"errors"
"fmt"
"net"
"os"
"strings"
"sync"
"time"
"github.com/jedisct1/dlog"
"github.com/miekg/dns"
lumberjack "gopkg.in/natefinch/lumberjack.v2"
)
type PluginQueryLog struct {
sync.Mutex
outFd *os.File
logger *lumberjack.Logger
format string
ignoredQtypes []string
}
......@@ -29,13 +27,7 @@ func (plugin *PluginQueryLog) Description() string {
}
func (plugin *PluginQueryLog) Init(proxy *Proxy) error {
plugin.Lock()
defer plugin.Unlock()
outFd, err := os.OpenFile(proxy.queryLogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
return err
}
plugin.outFd = outFd
plugin.logger = &lumberjack.Logger{LocalTime: true, MaxSize: proxy.logMaxSize, MaxAge: proxy.logMaxAge, MaxBackups: proxy.logMaxBackups, Filename: proxy.queryLogFile, Compress: true}
plugin.format = proxy.queryLogFormat
plugin.ignoredQtypes = proxy.queryLogIgnoredQtypes
......@@ -88,11 +80,9 @@ func (plugin *PluginQueryLog) Eval(pluginsState *PluginsState, msg *dns.Msg) err
} else {
dlog.Fatalf("Unexpected log format: [%s]", plugin.format)
}
plugin.Lock()
if plugin.outFd == nil {
if plugin.logger == nil {
return errors.New("Log file not initialized")
}
plugin.outFd.WriteString(line)
defer plugin.Unlock()
plugin.logger.Write([]byte(line))
return nil
}
......@@ -52,6 +52,9 @@ type Proxy struct {
maxClients uint32
xTransport *XTransport
allWeeklyRanges *map[string]WeeklyRanges
logMaxSize int
logMaxAge int
logMaxBackups int
}
func (proxy *Proxy) StartProxy() {
......
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
The MIT License (MIT)
Copyright (c) 2014 Nate Finch
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
\ No newline at end of file
# lumberjack [![GoDoc](https://godoc.org/gopkg.in/natefinch/lumberjack.v2?status.png)](https://godoc.org/gopkg.in/natefinch/lumberjack.v2) [![Build Status](https://drone.io/github.com/natefinch/lumberjack/status.png)](https://drone.io/github.com/natefinch/lumberjack/latest) [![Build status](https://ci.appveyor.com/api/projects/status/00gchpxtg4gkrt5d)](https://ci.appveyor.com/project/natefinch/lumberjack) [![Coverage Status](https://coveralls.io/repos/natefinch/lumberjack/badge.svg?branch=v2.0)](https://coveralls.io/r/natefinch/lumberjack?branch=v2.0)
### Lumberjack is a Go package for writing logs to rolling files.
Package lumberjack provides a rolling logger.
Note that this is v2.0 of lumberjack, and should be imported using gopkg.in
thusly:
import "gopkg.in/natefinch/lumberjack.v2"
The package name remains simply lumberjack, and the code resides at
https://github.com/natefinch/lumberjack under the v2.0 branch.
Lumberjack is intended to be one part of a logging infrastructure.
It is not an all-in-one solution, but instead is a pluggable
component at the bottom of the logging stack that simply controls the files
to which logs are written.
Lumberjack plays well with any logging package that can write to an
io.Writer, including the standard library's log package.
Lumberjack assumes that only one process is writing to the output files.
Using the same lumberjack configuration from multiple processes on the same
machine will result in improper behavior.
**Example**
To use lumberjack with the standard library's log package, just pass it into the SetOutput function when your application starts.
Code:
```go
log.SetOutput(&lumberjack.Logger{
Filename: "/var/log/myapp/foo.log",
MaxSize: 500, // megabytes
MaxBackups: 3,
MaxAge: 28, //days
})
```
## type Logger
``` go
type Logger struct {
// Filename is the file to write logs to. Backup log files will be retained
// in the same directory. It uses <processname>-lumberjack.log in
// os.TempDir() if empty.
Filename string `json:"filename" yaml:"filename"`
// MaxSize is the maximum size in megabytes of the log file before it gets
// rotated. It defaults to 100 megabytes.
MaxSize int `json:"maxsize" yaml:"maxsize"`
// MaxAge is the maximum number of days to retain old log files based on the
// timestamp encoded in their filename. Note that a day is defined as 24
// hours and may not exactly correspond to calendar days due to daylight
// savings, leap seconds, etc. The default is not to remove old log files
// based on age.
MaxAge int `json:"maxage" yaml:"maxage"`
// MaxBackups is the maximum number of old log files to retain. The default
// is to retain all old log files (though MaxAge may still cause them to get
// deleted.)
MaxBackups int `json:"maxbackups" yaml:"maxbackups"`
// LocalTime determines if the time used for formatting the timestamps in
// backup files is the computer's local time. The default is to use UTC
// time.
LocalTime bool `json:"localtime" yaml:"localtime"`
// contains filtered or unexported fields
}
```
Logger is an io.WriteCloser that writes to the specified filename.
Logger opens or creates the logfile on first Write. If the file exists and
is less than MaxSize megabytes, lumberjack will open and append to that file.
If the file exists and its size is >= MaxSize megabytes, the file is renamed
by putting the current time in a timestamp in the name immediately before the
file's extension (or the end of the filename if there's no extension). A new
log file is then created using original filename.
Whenever a write would cause the current log file exceed MaxSize megabytes,
the current file is closed, renamed, and a new log file created with the
original name. Thus, the filename you give Logger is always the "current" log
file.
Backups use the log file name given to Logger, in the form `name-timestamp.ext`
where name is the filename without the extension, timestamp is the time at which
the log was rotated formatted with the time.Time format of
`2006-01-02T15-04-05.000` and the extension is the original extension. For
example, if your Logger.Filename is `/var/log/foo/server.log`, a backup created
at 6:30pm on Nov 11 2016 would use the filename
`/var/log/foo/server-2016-11-04T18-30-00.000.log`
### Cleaning Up Old Log Files
Whenever a new logfile gets created, old log files may be deleted. The most
recent files according to the encoded timestamp will be retained, up to a
number equal to MaxBackups (or all of them if MaxBackups is 0). Any files
with an encoded timestamp older than MaxAge days are deleted, regardless of
MaxBackups. Note that the time encoded in the timestamp is the rotation
time, which may differ from the last time that file was written to.
If MaxBackups and MaxAge are both 0, no old log files will be deleted.
### func (\*Logger) Close
``` go
func (l *Logger) Close() error
```
Close implements io.Closer, and closes the current logfile.
### func (\*Logger) Rotate
``` go
func (l *Logger) Rotate() error
```
Rotate causes Logger to close the existing log file and immediately create a
new one. This is a helper function for applications that want to initiate
rotations outside of the normal rotation rules, such as in response to
SIGHUP. After rotating, this initiates a cleanup of old log files according
to the normal rules.
**Example**
Example of how to rotate in response to SIGHUP.
Code:
```go
l := &lumberjack.Logger{}
log.SetOutput(l)
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP)
go func() {
for {
<-c
l.Rotate()
}
}()
```
### func (\*Logger) Write
``` go
func (l *Logger) Write(p []byte) (n int, err error)
```
Write implements io.Writer. If a write would cause the log file to be larger
than MaxSize, the file is closed, renamed to include a timestamp of the
current time, and a new log file is created using the original log file name.
If the length of the write is greater than MaxSize, an error is returned.
- - -
Generated by [godoc2md](http://godoc.org/github.com/davecheney/godoc2md)
// +build !linux
package lumberjack
import (
"os"
)
func chown(_ string, _ os.FileInfo) error {
return nil
}
package lumberjack
import (
"os"
"syscall"
)
// os_Chown is a var so we can mock it out during tests.
var os_Chown = os.Chown
func chown(name string, info os.FileInfo) error {
f, err := os.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, info.Mode())
if err != nil {
return err
}
f.Close()
stat := info.Sys().(*syscall.Stat_t)
return os_Chown(name, int(stat.Uid), int(stat.Gid))
}
package lumberjack_test
import (
"log"
"gopkg.in/natefinch/lumberjack.v2"
)
// To use lumberjack with the standard library's log package, just pass it into
// the SetOutput function when your application starts.
func Example() {
log.SetOutput(&lumberjack.Logger{
Filename: "/var/log/myapp/foo.log",
MaxSize: 500, // megabytes
MaxBackups: 3,
MaxAge: 28, // days
})
}
// +build linux
package lumberjack
import (
"os"
"syscall"
"testing"
"time"
)
func TestMaintainMode(t *testing.T) {
currentTime = fakeTime
dir := makeTempDir("TestMaintainMode", t)
defer os.RemoveAll(dir)
filename := logFile(dir)
mode := os.FileMode(0600)
f, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, mode)
isNil(err, t)
f.Close()
l := &Logger{
Filename: filename,
MaxBackups: 1,
MaxSize: 100, // megabytes
}
defer l.Close()
b := []byte("boo!")
n, err := l.Write(b)
isNil(err, t)
equals(len(b), n, t)
newFakeTime()
err = l.Rotate()
isNil(err, t)
filename2 := backupFile(dir)
info, err := os.Stat(filename)
isNil(err, t)
info2, err := os.Stat(filename2)
isNil(err, t)
equals(mode, info.Mode(), t)
equals(mode, info2.Mode(), t)
}
func TestMaintainOwner(t *testing.T) {
fakeFS := newFakeFS()
os_Chown = fakeFS.Chown
os_Stat = fakeFS.Stat
defer func() {
os_Chown = os.Chown
os_Stat = os.Stat
}()
currentTime = fakeTime
dir := makeTempDir("TestMaintainOwner", t)
defer os.RemoveAll(dir)
filename := logFile(dir)
f, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, 0644)
isNil(err, t)
f.Close()
l := &Logger{
Filename: filename,
MaxBackups: 1,
MaxSize: 100, // megabytes
}
defer l.Close()
b := []byte("boo!")
n, err := l.Write(b)
isNil(err, t)
equals(len(b), n, t)
newFakeTime()
err = l.Rotate()
isNil(err, t)
equals(555, fakeFS.files[filename].uid, t)
equals(666, fakeFS.files[filename].gid, t)
}
func TestCompressMaintainMode(t *testing.T) {
currentTime = fakeTime
dir := makeTempDir("TestCompressMaintainMode", t)
defer os.RemoveAll(dir)
filename := logFile(dir)
mode := os.FileMode(0600)
f, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, mode)
isNil(err, t)
f.Close()
l := &Logger{
Compress: true,
Filename: filename,
MaxBackups: 1,
MaxSize: 100, // megabytes
}
defer l.Close()
b := []byte("boo!")
n, err := l.Write(b)
isNil(err, t)
equals(len(b), n, t)
newFakeTime()
err = l.Rotate()
isNil(err, t)
// we need to wait a little bit since the files get compressed on a different
// goroutine.
<-time.After(10 * time.Millisecond)
// a compressed version of the log file should now exist with the correct
// mode.
filename2 := backupFile(dir)
info, err := os.Stat(filename)
isNil(err, t)
info2, err := os.Stat(filename2+compressSuffix)
isNil(err, t)
equals(mode, info.Mode(), t)
equals(mode, info2.Mode(), t)
}
func TestCompressMaintainOwner(t *testing.T) {
fakeFS := newFakeFS()
os_Chown = fakeFS.Chown
os_Stat = fakeFS.Stat
defer func() {
os_Chown = os.Chown
os_Stat = os.Stat
}()
currentTime = fakeTime
dir := makeTempDir("TestCompressMaintainOwner", t)
defer os.RemoveAll(dir)
filename := logFile(dir)