file.go 6.2 KB
Newer Older
A
astaxie 已提交
1
// Copyright 2014 beego Author. All Rights Reserved.
A
astaxie 已提交
2
//
A
astaxie 已提交
3 4 5
// 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
A
astaxie 已提交
6
//
A
astaxie 已提交
7
//      http://www.apache.org/licenses/LICENSE-2.0
A
astaxie 已提交
8
//
A
astaxie 已提交
9 10 11 12 13 14
// 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.

A
astaxie 已提交
15 16 17
package logs

import (
D
DeanThompson 已提交
18
	"bytes"
A
astaxie 已提交
19 20 21
	"encoding/json"
	"errors"
	"fmt"
D
DeanThompson 已提交
22
	"io"
A
astaxie 已提交
23 24 25 26 27 28 29 30
	"log"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"time"
)

F
FuXiaoHei 已提交
31 32
// FileLogWriter implements LoggerInterface.
// It writes messages by lines limit, file size limit, or time frequency.
A
astaxie 已提交
33 34 35 36
type FileLogWriter struct {
	*log.Logger
	mw *MuxWriter
	// The opened file
1
1fei 已提交
37
	Filename string `json:"filename"`
A
astaxie 已提交
38

1
1fei 已提交
39
	Maxlines          int `json:"maxlines"`
A
astaxie 已提交
40 41 42
	maxlines_curlines int

	// Rotate at size
1
1fei 已提交
43
	Maxsize         int `json:"maxsize"`
A
astaxie 已提交
44 45 46
	maxsize_cursize int

	// Rotate daily
1
1fei 已提交
47
	Daily          bool  `json:"daily"`
A
astaxie 已提交
48
	Maxdays        int64 `json:"maxdays"`
A
astaxie 已提交
49 50
	daily_opendate int

1
1fei 已提交
51
	Rotate bool `json:"rotate"`
A
astaxie 已提交
52 53 54

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

1
1fei 已提交
55
	Level int `json:"level"`
A
astaxie 已提交
56 57
}

F
FuXiaoHei 已提交
58
// an *os.File writer with locker.
A
astaxie 已提交
59 60 61 62 63
type MuxWriter struct {
	sync.Mutex
	fd *os.File
}

F
FuXiaoHei 已提交
64
// write to os.File.
A
astaxie 已提交
65 66 67 68 69 70
func (l *MuxWriter) Write(b []byte) (int, error) {
	l.Lock()
	defer l.Unlock()
	return l.fd.Write(b)
}

F
FuXiaoHei 已提交
71
// set os.File in writer.
A
astaxie 已提交
72 73 74 75 76 77 78
func (l *MuxWriter) SetFd(fd *os.File) {
	if l.fd != nil {
		l.fd.Close()
	}
	l.fd = fd
}

F
FuXiaoHei 已提交
79
// create a FileLogWriter returning as LoggerInterface.
A
astaxie 已提交
80 81
func NewFileWriter() LoggerInterface {
	w := &FileLogWriter{
1
1fei 已提交
82 83 84 85 86 87 88
		Filename: "",
		Maxlines: 1000000,
		Maxsize:  1 << 28, //256 MB
		Daily:    true,
		Maxdays:  7,
		Rotate:   true,
		Level:    LevelTrace,
A
astaxie 已提交
89 90 91 92 93 94 95 96
	}
	// 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 已提交
97 98 99
// Init file logger with json config.
// jsonconfig like:
//	{
A
astaxie 已提交
100 101 102 103 104 105
//	"filename":"logs/beego.log",
//	"maxlines":10000,
//	"maxsize":1<<30,
//	"daily":true,
//	"maxdays":15,
//	"rotate":true
F
FuXiaoHei 已提交
106
//	}
A
astaxie 已提交
107
func (w *FileLogWriter) Init(jsonconfig string) error {
1
1fei 已提交
108
	err := json.Unmarshal([]byte(jsonconfig), w)
A
astaxie 已提交
109 110 111
	if err != nil {
		return err
	}
1
1fei 已提交
112
	if len(w.Filename) == 0 {
A
astaxie 已提交
113 114
		return errors.New("jsonconfig must have filename")
	}
A
asta.xie 已提交
115
	err = w.startLogger()
A
astaxie 已提交
116 117 118
	return err
}

F
FuXiaoHei 已提交
119
// start file logger. create log file and set to locker-inside file writer.
A
asta.xie 已提交
120
func (w *FileLogWriter) startLogger() error {
A
astaxie 已提交
121 122 123 124 125
	fd, err := w.createLogFile()
	if err != nil {
		return err
	}
	w.mw.SetFd(fd)
F
fuxiaohei 已提交
126
	return w.initFd()
A
astaxie 已提交
127 128 129 130 131
}

func (w *FileLogWriter) docheck(size int) {
	w.startLock.Lock()
	defer w.startLock.Unlock()
A
asta.xie 已提交
132
	if w.Rotate && ((w.Maxlines > 0 && w.maxlines_curlines >= w.Maxlines) ||
1
1fei 已提交
133
		(w.Maxsize > 0 && w.maxsize_cursize >= w.Maxsize) ||
A
asta.xie 已提交
134
		(w.Daily && time.Now().Day() != w.daily_opendate)) {
A
astaxie 已提交
135
		if err := w.DoRotate(); err != nil {
1
1fei 已提交
136
			fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.Filename, err)
A
astaxie 已提交
137 138 139 140 141 142 143
			return
		}
	}
	w.maxlines_curlines++
	w.maxsize_cursize += size
}

F
FuXiaoHei 已提交
144
// write logger message into file.
A
astaxie 已提交
145
func (w *FileLogWriter) WriteMsg(msg string, level int) error {
146
	if level > w.Level {
A
astaxie 已提交
147 148 149 150 151 152 153 154 155 156
		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 已提交
157
	fd, err := os.OpenFile(w.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)
A
astaxie 已提交
158 159 160 161 162 163 164 165 166 167 168
	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()
F
fuxiaohei 已提交
169
	w.maxlines_curlines = 0
A
astaxie 已提交
170
	if finfo.Size() > 0 {
D
DeanThompson 已提交
171
		count, err := w.lines()
A
astaxie 已提交
172 173 174
		if err != nil {
			return err
		}
D
DeanThompson 已提交
175
		w.maxlines_curlines = count
A
astaxie 已提交
176 177 178 179
	}
	return nil
}

D
DeanThompson 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
func (w *FileLogWriter) lines() (int, error) {
	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
}

F
FuXiaoHei 已提交
207 208
// DoRotate means it need to write file in new file.
// new file name like xx.log.2013-01-01.2
A
astaxie 已提交
209
func (w *FileLogWriter) DoRotate() error {
1
1fei 已提交
210
	_, err := os.Lstat(w.Filename)
A
astaxie 已提交
211 212 213 214 215
	if err == nil { // file exists
		// Find the next available number
		num := 1
		fname := ""
		for ; err == nil && num <= 999; num++ {
1
1fei 已提交
216
			fname = w.Filename + fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), num)
A
astaxie 已提交
217 218 219 220
			_, err = os.Lstat(fname)
		}
		// return error if the last file checked still existed
		if err == nil {
1
1fei 已提交
221
			return fmt.Errorf("Rotate: Cannot find free log number to rename %s\n", w.Filename)
A
astaxie 已提交
222 223 224 225 226 227 228 229 230 231 232
		}

		// 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 已提交
233
		err = os.Rename(w.Filename, fname)
A
astaxie 已提交
234 235 236 237 238
		if err != nil {
			return fmt.Errorf("Rotate: %s\n", err)
		}

		// re-start logger
A
asta.xie 已提交
239
		err = w.startLogger()
A
astaxie 已提交
240 241 242 243 244 245 246 247 248 249 250
		if err != nil {
			return fmt.Errorf("Rotate StartLogger: %s\n", err)
		}

		go w.deleteOldLog()
	}

	return nil
}

func (w *FileLogWriter) deleteOldLog() {
251
	dir := filepath.Dir(w.Filename)
F
Francois 已提交
252 253 254 255 256 257 258 259
	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)
			}
		}()

1
1fei 已提交
260 261
		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 已提交
262 263 264
				os.Remove(path)
			}
		}
F
Francois 已提交
265
		return
A
astaxie 已提交
266 267 268
	})
}

F
FuXiaoHei 已提交
269
// destroy file logger, close file writer.
A
astaxie 已提交
270 271 272 273
func (w *FileLogWriter) Destroy() {
	w.mw.fd.Close()
}

F
FuXiaoHei 已提交
274 275 276
// flush file logger.
// there are no buffering messages in file logger in memory.
// flush file means sync file from disk.
A
astaxie 已提交
277 278 279 280
func (w *FileLogWriter) Flush() {
	w.mw.fd.Sync()
}

A
astaxie 已提交
281 282 283
func init() {
	Register("file", NewFileWriter)
}