1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-29 13:41:28 +00:00
Beego/logs/file.go

289 lines
6.4 KiB
Go
Raw Normal View History

2014-08-18 08:41:43 +00:00
// Copyright 2014 beego Author. All Rights Reserved.
2014-07-03 15:40:21 +00:00
//
2014-08-18 08:41:43 +00:00
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
2014-07-03 15:40:21 +00:00
//
2014-08-18 08:41:43 +00:00
// http://www.apache.org/licenses/LICENSE-2.0
2014-07-03 15:40:21 +00:00
//
2014-08-18 08:41:43 +00:00
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2013-08-27 15:48:58 +00:00
package logs
import (
2014-11-21 10:12:39 +00:00
"bytes"
2013-08-27 15:48:58 +00:00
"encoding/json"
"errors"
"fmt"
2014-11-21 10:12:39 +00:00
"io"
2013-08-27 15:48:58 +00:00
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
2015-09-11 15:08:24 +00:00
// fileLogWriter implements LoggerInterface.
2013-12-30 15:32:57 +00:00
// It writes messages by lines limit, file size limit, or time frequency.
2015-09-11 15:08:24 +00:00
type fileLogWriter struct {
2013-08-27 15:48:58 +00:00
*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
2015-09-11 15:08:24 +00:00
Maxlines int `json:"maxlines"`
maxlinesCurlines int
2013-08-27 15:48:58 +00:00
// Rotate at size
2015-09-11 15:08:24 +00:00
Maxsize int `json:"maxsize"`
maxsizeCursize int
2013-08-27 15:48:58 +00:00
// Rotate daily
2015-09-11 15:08:24 +00:00
Daily bool `json:"daily"`
Maxdays int64 `json:"maxdays"`
dailyOpendate int
2013-08-27 15:48:58 +00:00
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
}
2015-09-11 15:08:24 +00:00
// MuxWriter is 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)
}
2015-09-11 15:08:24 +00:00
// SetFd 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
}
2015-09-11 15:08:24 +00:00
// NewFileWriter create a FileLogWriter returning as LoggerInterface.
func newFileWriter() Logger {
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
// }
2015-09-11 15:08:24 +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.
2015-09-11 15:08:24 +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)
2015-02-23 03:42:46 +00:00
return w.initFd()
2013-08-27 15:48:58 +00:00
}
2015-09-11 15:08:24 +00:00
func (w *fileLogWriter) docheck(size int) {
2013-08-27 15:48:58 +00:00
w.startLock.Lock()
defer w.startLock.Unlock()
2015-09-11 15:08:24 +00:00
if w.Rotate && ((w.Maxlines > 0 && w.maxlinesCurlines >= w.Maxlines) ||
(w.Maxsize > 0 && w.maxsizeCursize >= w.Maxsize) ||
(w.Daily && time.Now().Day() != w.dailyOpendate)) {
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
}
}
2015-09-11 15:08:24 +00:00
w.maxlinesCurlines++
w.maxsizeCursize += size
2013-08-27 15:48:58 +00:00
}
2015-09-11 15:08:24 +00:00
// WriteMsg write logger message into file.
func (w *fileLogWriter) WriteMsg(msg string, level int) error {
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
}
2015-09-11 15:08:24 +00:00
func (w *fileLogWriter) createLogFile() (*os.File, error) {
2013-08-27 15:48:58 +00:00
// 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
}
2015-09-11 15:08:24 +00:00
func (w *fileLogWriter) initFd() error {
2013-08-27 15:48:58 +00:00
fd := w.mw.fd
finfo, err := fd.Stat()
if err != nil {
return fmt.Errorf("get stat err: %s\n", err)
}
2015-09-11 15:08:24 +00:00
w.maxsizeCursize = int(finfo.Size())
w.dailyOpendate = time.Now().Day()
w.maxlinesCurlines = 0
2013-08-27 15:48:58 +00:00
if finfo.Size() > 0 {
2014-11-21 10:12:39 +00:00
count, err := w.lines()
2013-08-27 15:48:58 +00:00
if err != nil {
return err
}
2015-09-11 15:08:24 +00:00
w.maxlinesCurlines = count
2013-08-27 15:48:58 +00:00
}
return nil
}
2015-09-11 15:08:24 +00:00
func (w *fileLogWriter) lines() (int, error) {
2014-11-21 10:12:39 +00:00
fd, err := os.Open(w.Filename)
if err != nil {
return 0, err
}
defer fd.Close()
buf := make([]byte, 32768) // 32k
count := 0
lineSep := []byte{'\n'}
for {
c, err := fd.Read(buf)
if err != nil && err != io.EOF {
return count, err
}
count += bytes.Count(buf[:c], lineSep)
if err == io.EOF {
break
}
}
return count, nil
}
2013-12-30 15:32:57 +00:00
// DoRotate means it need to write file in new file.
// new file name like xx.2013-01-01.2.log
2015-09-11 15:08:24 +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 := ""
suffix := filepath.Ext(w.Filename)
filenameOnly := strings.TrimSuffix(w.Filename, suffix)
if suffix == "" {
suffix = ".log"
}
2013-08-27 15:48:58 +00:00
for ; err == nil && num <= 999; num++ {
fname = filenameOnly + fmt.Sprintf(".%s.%03d%s", time.Now().Format("2006-01-02"), num, suffix)
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
}
2015-09-11 15:08:24 +00:00
func (w *fileLogWriter) deleteOldLog() {
dir := filepath.Dir(w.Filename)
filepath.Walk(dir, func(path string, info os.FileInfo, err error) (returnErr error) {
defer func() {
if r := recover(); r != nil {
returnErr = fmt.Errorf("Unable to delete old log '%s', error: %+v", path, r)
fmt.Println(returnErr)
}
}()
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
2013-08-27 15:48:58 +00:00
})
}
2015-09-11 15:08:24 +00:00
// Destroy close the file desciption, close file writer.
func (w *fileLogWriter) Destroy() {
2013-08-27 15:48:58 +00:00
w.mw.fd.Close()
}
2015-09-11 15:08:24 +00:00
// Flush flush file logger.
2013-12-30 15:32:57 +00:00
// there are no buffering messages in file logger in memory.
// flush file means sync file from disk.
2015-09-11 15:08:24 +00:00
func (w *fileLogWriter) Flush() {
2013-11-27 09:50:10 +00:00
w.mw.fd.Sync()
}
2013-08-27 15:48:58 +00:00
func init() {
2015-09-11 15:08:24 +00:00
Register("file", newFileWriter)
2013-08-27 15:48:58 +00:00
}