1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-24 22:40:55 +00:00
Beego/logs/file.go

240 lines
5.2 KiB
Go
Raw Normal View History

2013-08-27 15:48:58 +00:00
package logs
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
2013-12-30 15:32:57 +00:00
// FileLogWriter implements LoggerInterface.
// It writes messages by lines limit, file size limit, or time frequency.
2013-08-27 15:48:58 +00:00
type FileLogWriter struct {
*log.Logger
mw *MuxWriter
// The opened file
2013-12-19 10:15:46 +00:00
Filename string `json:"filename"`
2013-08-27 15:48:58 +00:00
2013-12-19 10:15:46 +00:00
Maxlines int `json:"maxlines"`
2013-08-27 15:48:58 +00:00
maxlines_curlines int
// Rotate at size
2013-12-19 10:15:46 +00:00
Maxsize int `json:"maxsize"`
2013-08-27 15:48:58 +00:00
maxsize_cursize int
// Rotate daily
2013-12-19 10:15:46 +00:00
Daily bool `json:"daily"`
Maxdays int64 `json:"maxdays`
2013-08-27 15:48:58 +00:00
daily_opendate int
2013-12-19 10:15:46 +00:00
Rotate bool `json:"rotate"`
2013-08-27 15:48:58 +00:00
startLock sync.Mutex // Only one log can write to the file
2013-12-19 10:15:46 +00:00
Level int `json:"level"`
2013-08-27 15:48:58 +00:00
}
2013-12-30 15:32:57 +00:00
// an *os.File writer with locker.
2013-08-27 15:48:58 +00:00
type MuxWriter struct {
sync.Mutex
fd *os.File
}
2013-12-30 15:32:57 +00:00
// write to os.File.
2013-08-27 15:48:58 +00:00
func (l *MuxWriter) Write(b []byte) (int, error) {
l.Lock()
defer l.Unlock()
return l.fd.Write(b)
}
2013-12-30 15:32:57 +00:00
// set os.File in writer.
2013-08-27 15:48:58 +00:00
func (l *MuxWriter) SetFd(fd *os.File) {
if l.fd != nil {
l.fd.Close()
}
l.fd = fd
}
2013-12-30 15:32:57 +00:00
// create a FileLogWriter returning as LoggerInterface.
2013-08-27 15:48:58 +00:00
func NewFileWriter() LoggerInterface {
w := &FileLogWriter{
2013-12-19 10:15:46 +00:00
Filename: "",
Maxlines: 1000000,
Maxsize: 1 << 28, //256 MB
Daily: true,
Maxdays: 7,
Rotate: true,
Level: LevelTrace,
2013-08-27 15:48:58 +00:00
}
// 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
}
2013-12-30 15:32:57 +00:00
// Init file logger with json config.
// jsonconfig like:
// {
2013-08-27 15:48:58 +00:00
// "filename":"logs/beego.log",
// "maxlines":10000,
// "maxsize":1<<30,
// "daily":true,
// "maxdays":15,
// "rotate":true
2013-12-30 15:32:57 +00:00
// }
2013-08-27 15:48:58 +00:00
func (w *FileLogWriter) Init(jsonconfig string) error {
2013-12-19 10:15:46 +00:00
err := json.Unmarshal([]byte(jsonconfig), w)
2013-08-27 15:48:58 +00:00
if err != nil {
return err
}
2013-12-19 10:15:46 +00:00
if len(w.Filename) == 0 {
2013-08-27 15:48:58 +00:00
return errors.New("jsonconfig must have filename")
}
2014-04-02 15:43:37 +00:00
err = w.startLogger()
2013-08-27 15:48:58 +00:00
return err
}
2013-12-30 15:32:57 +00:00
// start file logger. create log file and set to locker-inside file writer.
2014-04-02 15:43:37 +00:00
func (w *FileLogWriter) startLogger() error {
2013-08-27 15:48:58 +00:00
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()
2014-03-21 06:07:03 +00:00
if w.Rotate && ((w.Maxlines > 0 && w.maxlines_curlines >= w.Maxlines) ||
2013-12-19 10:15:46 +00:00
(w.Maxsize > 0 && w.maxsize_cursize >= w.Maxsize) ||
2014-03-21 06:07:03 +00:00
(w.Daily && time.Now().Day() != w.daily_opendate)) {
2013-08-27 15:48:58 +00:00
if err := w.DoRotate(); err != nil {
2013-12-19 10:15:46 +00:00
fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.Filename, err)
2013-08-27 15:48:58 +00:00
return
}
}
w.maxlines_curlines++
w.maxsize_cursize += size
}
2013-12-30 15:32:57 +00:00
// write logger message into file.
2013-08-27 15:48:58 +00:00
func (w *FileLogWriter) WriteMsg(msg string, level int) error {
2013-12-19 10:15:46 +00:00
if level < w.Level {
2013-08-27 15:48:58 +00:00
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
2013-12-19 10:15:46 +00:00
fd, err := os.OpenFile(w.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)
2013-08-27 15:48:58 +00:00
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 {
2013-12-19 10:15:46 +00:00
content, err := ioutil.ReadFile(w.Filename)
2013-08-27 15:48:58 +00:00
if err != nil {
return err
}
w.maxlines_curlines = len(strings.Split(string(content), "\n"))
} else {
w.maxlines_curlines = 0
}
return nil
}
2013-12-30 15:32:57 +00:00
// DoRotate means it need to write file in new file.
// new file name like xx.log.2013-01-01.2
2013-08-27 15:48:58 +00:00
func (w *FileLogWriter) DoRotate() error {
2013-12-19 10:15:46 +00:00
_, err := os.Lstat(w.Filename)
2013-08-27 15:48:58 +00:00
if err == nil { // file exists
// Find the next available number
num := 1
fname := ""
for ; err == nil && num <= 999; num++ {
2013-12-19 10:15:46 +00:00
fname = w.Filename + fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), num)
2013-08-27 15:48:58 +00:00
_, err = os.Lstat(fname)
}
// return error if the last file checked still existed
if err == nil {
2013-12-19 10:15:46 +00:00
return fmt.Errorf("Rotate: Cannot find free log number to rename %s\n", w.Filename)
2013-08-27 15:48:58 +00:00
}
// 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
2013-12-19 10:15:46 +00:00
err = os.Rename(w.Filename, fname)
2013-08-27 15:48:58 +00:00
if err != nil {
return fmt.Errorf("Rotate: %s\n", err)
}
// re-start logger
2014-04-02 15:43:37 +00:00
err = w.startLogger()
2013-08-27 15:48:58 +00:00
if err != nil {
return fmt.Errorf("Rotate StartLogger: %s\n", err)
}
go w.deleteOldLog()
}
return nil
}
func (w *FileLogWriter) deleteOldLog() {
dir := filepath.Dir(w.Filename)
2013-08-27 15:48:58 +00:00
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
2013-12-19 10:15:46 +00:00
if !info.IsDir() && info.ModTime().Unix() < (time.Now().Unix()-60*60*24*w.Maxdays) {
if strings.HasPrefix(filepath.Base(path), filepath.Base(w.Filename)) {
2013-08-27 15:48:58 +00:00
os.Remove(path)
}
}
return nil
})
}
2013-12-30 15:32:57 +00:00
// destroy file logger, close file writer.
2013-08-27 15:48:58 +00:00
func (w *FileLogWriter) Destroy() {
w.mw.fd.Close()
}
2013-12-30 15:32:57 +00:00
// flush file logger.
// there are no buffering messages in file logger in memory.
// flush file means sync file from disk.
2013-11-27 09:50:10 +00:00
func (w *FileLogWriter) Flush() {
w.mw.fd.Sync()
}
2013-08-27 15:48:58 +00:00
func init() {
Register("file", NewFileWriter)
}