file.go 5.2 KB
Newer Older
A
astaxie 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
package logs

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"time"
)

F
FuXiaoHei 已提交
16 17
// FileLogWriter implements LoggerInterface.
// It writes messages by lines limit, file size limit, or time frequency.
A
astaxie 已提交
18 19 20 21
type FileLogWriter struct {
	*log.Logger
	mw *MuxWriter
	// The opened file
1
1fei 已提交
22
	Filename string `json:"filename"`
A
astaxie 已提交
23

1
1fei 已提交
24
	Maxlines          int `json:"maxlines"`
A
astaxie 已提交
25 26 27
	maxlines_curlines int

	// Rotate at size
1
1fei 已提交
28
	Maxsize         int `json:"maxsize"`
A
astaxie 已提交
29 30 31
	maxsize_cursize int

	// Rotate daily
1
1fei 已提交
32 33
	Daily          bool  `json:"daily"`
	Maxdays        int64 `json:"maxdays`
A
astaxie 已提交
34 35
	daily_opendate int

1
1fei 已提交
36
	Rotate bool `json:"rotate"`
A
astaxie 已提交
37 38 39

	startLock sync.Mutex // Only one log can write to the file

1
1fei 已提交
40
	Level int `json:"level"`
A
astaxie 已提交
41 42
}

F
FuXiaoHei 已提交
43
// an *os.File writer with locker.
A
astaxie 已提交
44 45 46 47 48
type MuxWriter struct {
	sync.Mutex
	fd *os.File
}

F
FuXiaoHei 已提交
49
// write to os.File.
A
astaxie 已提交
50 51 52 53 54 55
func (l *MuxWriter) Write(b []byte) (int, error) {
	l.Lock()
	defer l.Unlock()
	return l.fd.Write(b)
}

F
FuXiaoHei 已提交
56
// set os.File in writer.
A
astaxie 已提交
57 58 59 60 61 62 63
func (l *MuxWriter) SetFd(fd *os.File) {
	if l.fd != nil {
		l.fd.Close()
	}
	l.fd = fd
}

F
FuXiaoHei 已提交
64
// create a FileLogWriter returning as LoggerInterface.
A
astaxie 已提交
65 66
func NewFileWriter() LoggerInterface {
	w := &FileLogWriter{
1
1fei 已提交
67 68 69 70 71 72 73
		Filename: "",
		Maxlines: 1000000,
		Maxsize:  1 << 28, //256 MB
		Daily:    true,
		Maxdays:  7,
		Rotate:   true,
		Level:    LevelTrace,
A
astaxie 已提交
74 75 76 77 78 79 80 81
	}
	// use MuxWriter instead direct use os.File for lock write when rotate
	w.mw = new(MuxWriter)
	// set MuxWriter as Logger's io.Writer
	w.Logger = log.New(w.mw, "", log.Ldate|log.Ltime)
	return w
}

F
FuXiaoHei 已提交
82 83 84
// Init file logger with json config.
// jsonconfig like:
//	{
A
astaxie 已提交
85 86 87 88 89 90
//	"filename":"logs/beego.log",
//	"maxlines":10000,
//	"maxsize":1<<30,
//	"daily":true,
//	"maxdays":15,
//	"rotate":true
F
FuXiaoHei 已提交
91
//	}
A
astaxie 已提交
92
func (w *FileLogWriter) Init(jsonconfig string) error {
1
1fei 已提交
93
	err := json.Unmarshal([]byte(jsonconfig), w)
A
astaxie 已提交
94 95 96
	if err != nil {
		return err
	}
1
1fei 已提交
97
	if len(w.Filename) == 0 {
A
astaxie 已提交
98 99 100 101 102 103
		return errors.New("jsonconfig must have filename")
	}
	err = w.StartLogger()
	return err
}

F
FuXiaoHei 已提交
104
// start file logger. create log file and set to locker-inside file writer.
A
astaxie 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
func (w *FileLogWriter) StartLogger() error {
	fd, err := w.createLogFile()
	if err != nil {
		return err
	}
	w.mw.SetFd(fd)
	err = w.initFd()
	if err != nil {
		return err
	}
	return nil
}

func (w *FileLogWriter) docheck(size int) {
	w.startLock.Lock()
	defer w.startLock.Unlock()
1
1fei 已提交
121 122 123
	if (w.Maxlines > 0 && w.maxlines_curlines >= w.Maxlines) ||
		(w.Maxsize > 0 && w.maxsize_cursize >= w.Maxsize) ||
		(w.Daily && time.Now().Day() != w.daily_opendate) {
A
astaxie 已提交
124
		if err := w.DoRotate(); err != nil {
1
1fei 已提交
125
			fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.Filename, err)
A
astaxie 已提交
126 127 128 129 130 131 132
			return
		}
	}
	w.maxlines_curlines++
	w.maxsize_cursize += size
}

F
FuXiaoHei 已提交
133
// write logger message into file.
A
astaxie 已提交
134
func (w *FileLogWriter) WriteMsg(msg string, level int) error {
1
1fei 已提交
135
	if level < w.Level {
A
astaxie 已提交
136 137 138 139 140 141 142 143 144 145
		return nil
	}
	n := 24 + len(msg) // 24 stand for the length "2013/06/23 21:00:22 [T] "
	w.docheck(n)
	w.Logger.Println(msg)
	return nil
}

func (w *FileLogWriter) createLogFile() (*os.File, error) {
	// Open the log file
1
1fei 已提交
146
	fd, err := os.OpenFile(w.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)
A
astaxie 已提交
147 148 149 150 151 152 153 154 155 156 157 158
	return fd, err
}

func (w *FileLogWriter) initFd() error {
	fd := w.mw.fd
	finfo, err := fd.Stat()
	if err != nil {
		return fmt.Errorf("get stat err: %s\n", err)
	}
	w.maxsize_cursize = int(finfo.Size())
	w.daily_opendate = time.Now().Day()
	if finfo.Size() > 0 {
1
1fei 已提交
159
		content, err := ioutil.ReadFile(w.Filename)
A
astaxie 已提交
160 161 162 163 164 165 166 167 168 169
		if err != nil {
			return err
		}
		w.maxlines_curlines = len(strings.Split(string(content), "\n"))
	} else {
		w.maxlines_curlines = 0
	}
	return nil
}

F
FuXiaoHei 已提交
170 171
// DoRotate means it need to write file in new file.
// new file name like xx.log.2013-01-01.2
A
astaxie 已提交
172
func (w *FileLogWriter) DoRotate() error {
1
1fei 已提交
173
	_, err := os.Lstat(w.Filename)
A
astaxie 已提交
174 175 176 177 178
	if err == nil { // file exists
		// Find the next available number
		num := 1
		fname := ""
		for ; err == nil && num <= 999; num++ {
1
1fei 已提交
179
			fname = w.Filename + fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), num)
A
astaxie 已提交
180 181 182 183
			_, err = os.Lstat(fname)
		}
		// return error if the last file checked still existed
		if err == nil {
1
1fei 已提交
184
			return fmt.Errorf("Rotate: Cannot find free log number to rename %s\n", w.Filename)
A
astaxie 已提交
185 186 187 188 189 190 191 192 193 194 195
		}

		// block Logger's io.Writer
		w.mw.Lock()
		defer w.mw.Unlock()

		fd := w.mw.fd
		fd.Close()

		// close fd before rename
		// Rename the file to its newfound home
1
1fei 已提交
196
		err = os.Rename(w.Filename, fname)
A
astaxie 已提交
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
		if err != nil {
			return fmt.Errorf("Rotate: %s\n", err)
		}

		// re-start logger
		err = w.StartLogger()
		if err != nil {
			return fmt.Errorf("Rotate StartLogger: %s\n", err)
		}

		go w.deleteOldLog()
	}

	return nil
}

func (w *FileLogWriter) deleteOldLog() {
214
	dir := filepath.Dir(w.Filename)
A
astaxie 已提交
215
	filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
1
1fei 已提交
216 217
		if !info.IsDir() && info.ModTime().Unix() < (time.Now().Unix()-60*60*24*w.Maxdays) {
			if strings.HasPrefix(filepath.Base(path), filepath.Base(w.Filename)) {
A
astaxie 已提交
218 219 220 221 222 223 224
				os.Remove(path)
			}
		}
		return nil
	})
}

F
FuXiaoHei 已提交
225
// destroy file logger, close file writer.
A
astaxie 已提交
226 227 228 229
func (w *FileLogWriter) Destroy() {
	w.mw.fd.Close()
}

F
FuXiaoHei 已提交
230 231 232
// flush file logger.
// there are no buffering messages in file logger in memory.
// flush file means sync file from disk.
A
astaxie 已提交
233 234 235 236
func (w *FileLogWriter) Flush() {
	w.mw.fd.Sync()
}

A
astaxie 已提交
237 238 239
func init() {
	Register("file", NewFileWriter)
}