1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-22 23:20:54 +00:00

Merge pull request #390 from 1fei/master

更新logs的初始化部分
This commit is contained in:
astaxie 2013-12-19 02:54:37 -08:00
commit 67b9c63528
4 changed files with 64 additions and 132 deletions

View File

@ -10,45 +10,29 @@ import (
type ConnWriter struct { type ConnWriter struct {
lg *log.Logger lg *log.Logger
innerWriter io.WriteCloser innerWriter io.WriteCloser
reconnectOnMsg bool ReconnectOnMsg bool `json:"reconnectOnMsg"`
reconnect bool Reconnect bool `json:"reconnect"`
net string Net string `json:"net"`
addr string Addr string `json:"addr"`
level int Level int `json:"level"`
} }
func NewConn() LoggerInterface { func NewConn() LoggerInterface {
conn := new(ConnWriter) conn := new(ConnWriter)
conn.level = LevelTrace conn.Level = LevelTrace
return conn return conn
} }
func (c *ConnWriter) Init(jsonconfig string) error { func (c *ConnWriter) Init(jsonconfig string) error {
var m map[string]interface{} err := json.Unmarshal([]byte(jsonconfig), c)
err := json.Unmarshal([]byte(jsonconfig), &m)
if err != nil { if err != nil {
return err return err
} }
if rom, ok := m["reconnectOnMsg"]; ok {
c.reconnectOnMsg = rom.(bool)
}
if rc, ok := m["reconnect"]; ok {
c.reconnect = rc.(bool)
}
if nt, ok := m["net"]; ok {
c.net = nt.(string)
}
if addr, ok := m["addr"]; ok {
c.addr = addr.(string)
}
if lv, ok := m["level"]; ok {
c.level = int(lv.(float64))
}
return nil return nil
} }
func (c *ConnWriter) WriteMsg(msg string, level int) error { func (c *ConnWriter) WriteMsg(msg string, level int) error {
if level < c.level { if level < c.Level {
return nil return nil
} }
if c.neddedConnectOnMsg() { if c.neddedConnectOnMsg() {
@ -58,7 +42,7 @@ func (c *ConnWriter) WriteMsg(msg string, level int) error {
} }
} }
if c.reconnectOnMsg { if c.ReconnectOnMsg {
defer c.innerWriter.Close() defer c.innerWriter.Close()
} }
c.lg.Println(msg) c.lg.Println(msg)
@ -82,7 +66,7 @@ func (c *ConnWriter) connect() error {
c.innerWriter = nil c.innerWriter = nil
} }
conn, err := net.Dial(c.net, c.addr) conn, err := net.Dial(c.Net, c.Addr)
if err != nil { if err != nil {
return err return err
} }
@ -97,8 +81,8 @@ func (c *ConnWriter) connect() error {
} }
func (c *ConnWriter) neddedConnectOnMsg() bool { func (c *ConnWriter) neddedConnectOnMsg() bool {
if c.reconnect { if c.Reconnect {
c.reconnect = false c.Reconnect = false
return true return true
} }
@ -106,7 +90,7 @@ func (c *ConnWriter) neddedConnectOnMsg() bool {
return true return true
} }
return c.reconnectOnMsg return c.ReconnectOnMsg
} }
func init() { func init() {

View File

@ -8,30 +8,26 @@ import (
type ConsoleWriter struct { type ConsoleWriter struct {
lg *log.Logger lg *log.Logger
level int Level int `json:"level"`
} }
func NewConsole() LoggerInterface { func NewConsole() LoggerInterface {
cw := new(ConsoleWriter) cw := new(ConsoleWriter)
cw.lg = log.New(os.Stdout, "", log.Ldate|log.Ltime) cw.lg = log.New(os.Stdout, "", log.Ldate|log.Ltime)
cw.level = LevelTrace cw.Level = LevelTrace
return cw return cw
} }
func (c *ConsoleWriter) Init(jsonconfig string) error { func (c *ConsoleWriter) Init(jsonconfig string) error {
var m map[string]interface{} err := json.Unmarshal([]byte(jsonconfig), c)
err := json.Unmarshal([]byte(jsonconfig), &m)
if err != nil { if err != nil {
return err return err
} }
if lv, ok := m["level"]; ok {
c.level = int(lv.(float64))
}
return nil return nil
} }
func (c *ConsoleWriter) WriteMsg(msg string, level int) error { func (c *ConsoleWriter) WriteMsg(msg string, level int) error {
if level < c.level { if level < c.Level {
return nil return nil
} }
c.lg.Println(msg) c.lg.Println(msg)

View File

@ -18,25 +18,25 @@ type FileLogWriter struct {
*log.Logger *log.Logger
mw *MuxWriter mw *MuxWriter
// The opened file // The opened file
filename string Filename string `json:"filename"`
maxlines int Maxlines int `json:"maxlines"`
maxlines_curlines int maxlines_curlines int
// Rotate at size // Rotate at size
maxsize int Maxsize int `json:"maxsize"`
maxsize_cursize int maxsize_cursize int
// Rotate daily // Rotate daily
daily bool Daily bool `json:"daily"`
maxdays int64 Maxdays int64 `json:"maxdays`
daily_opendate int daily_opendate int
rotate bool Rotate bool `json:"rotate"`
startLock sync.Mutex // Only one log can write to the file startLock sync.Mutex // Only one log can write to the file
level int Level int `json:"level"`
} }
type MuxWriter struct { type MuxWriter struct {
@ -59,13 +59,13 @@ func (l *MuxWriter) SetFd(fd *os.File) {
func NewFileWriter() LoggerInterface { func NewFileWriter() LoggerInterface {
w := &FileLogWriter{ w := &FileLogWriter{
filename: "", Filename: "",
maxlines: 1000000, Maxlines: 1000000,
maxsize: 1 << 28, //256 MB Maxsize: 1 << 28, //256 MB
daily: true, Daily: true,
maxdays: 7, Maxdays: 7,
rotate: true, Rotate: true,
level: LevelTrace, Level: LevelTrace,
} }
// use MuxWriter instead direct use os.File for lock write when rotate // use MuxWriter instead direct use os.File for lock write when rotate
w.mw = new(MuxWriter) w.mw = new(MuxWriter)
@ -84,33 +84,12 @@ func NewFileWriter() LoggerInterface {
// "rotate":true // "rotate":true
//} //}
func (w *FileLogWriter) Init(jsonconfig string) error { func (w *FileLogWriter) Init(jsonconfig string) error {
var m map[string]interface{} err := json.Unmarshal([]byte(jsonconfig), w)
err := json.Unmarshal([]byte(jsonconfig), &m)
if err != nil { if err != nil {
return err return err
} }
if fn, ok := m["filename"]; !ok { if len(w.Filename) == 0 {
return errors.New("jsonconfig must have filename") return errors.New("jsonconfig must have filename")
} else {
w.filename = fn.(string)
}
if ml, ok := m["maxlines"]; ok {
w.maxlines = int(ml.(float64))
}
if ms, ok := m["maxsize"]; ok {
w.maxsize = int(ms.(float64))
}
if dl, ok := m["daily"]; ok {
w.daily = dl.(bool)
}
if md, ok := m["maxdays"]; ok {
w.maxdays = int64(md.(float64))
}
if rt, ok := m["rotate"]; ok {
w.rotate = rt.(bool)
}
if lv, ok := m["level"]; ok {
w.level = int(lv.(float64))
} }
err = w.StartLogger() err = w.StartLogger()
return err return err
@ -132,11 +111,11 @@ func (w *FileLogWriter) StartLogger() error {
func (w *FileLogWriter) docheck(size int) { func (w *FileLogWriter) docheck(size int) {
w.startLock.Lock() w.startLock.Lock()
defer w.startLock.Unlock() defer w.startLock.Unlock()
if (w.maxlines > 0 && w.maxlines_curlines >= w.maxlines) || if (w.Maxlines > 0 && w.maxlines_curlines >= w.Maxlines) ||
(w.maxsize > 0 && w.maxsize_cursize >= w.maxsize) || (w.Maxsize > 0 && w.maxsize_cursize >= w.Maxsize) ||
(w.daily && time.Now().Day() != w.daily_opendate) { (w.Daily && time.Now().Day() != w.daily_opendate) {
if err := w.DoRotate(); err != nil { if err := w.DoRotate(); err != nil {
fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.filename, err) fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.Filename, err)
return return
} }
} }
@ -145,7 +124,7 @@ func (w *FileLogWriter) docheck(size int) {
} }
func (w *FileLogWriter) WriteMsg(msg string, level int) error { func (w *FileLogWriter) WriteMsg(msg string, level int) error {
if level < w.level { if level < w.Level {
return nil return nil
} }
n := 24 + len(msg) // 24 stand for the length "2013/06/23 21:00:22 [T] " n := 24 + len(msg) // 24 stand for the length "2013/06/23 21:00:22 [T] "
@ -156,7 +135,7 @@ func (w *FileLogWriter) WriteMsg(msg string, level int) error {
func (w *FileLogWriter) createLogFile() (*os.File, error) { func (w *FileLogWriter) createLogFile() (*os.File, error) {
// Open the log file // Open the log file
fd, err := os.OpenFile(w.filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660) fd, err := os.OpenFile(w.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)
return fd, err return fd, err
} }
@ -169,7 +148,7 @@ func (w *FileLogWriter) initFd() error {
w.maxsize_cursize = int(finfo.Size()) w.maxsize_cursize = int(finfo.Size())
w.daily_opendate = time.Now().Day() w.daily_opendate = time.Now().Day()
if finfo.Size() > 0 { if finfo.Size() > 0 {
content, err := ioutil.ReadFile(w.filename) content, err := ioutil.ReadFile(w.Filename)
if err != nil { if err != nil {
return err return err
} }
@ -181,18 +160,18 @@ func (w *FileLogWriter) initFd() error {
} }
func (w *FileLogWriter) DoRotate() error { func (w *FileLogWriter) DoRotate() error {
_, err := os.Lstat(w.filename) _, err := os.Lstat(w.Filename)
if err == nil { // file exists if err == nil { // file exists
// Find the next available number // Find the next available number
num := 1 num := 1
fname := "" fname := ""
for ; err == nil && num <= 999; num++ { for ; err == nil && num <= 999; num++ {
fname = w.filename + fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), num) fname = w.Filename + fmt.Sprintf(".%s.%03d", time.Now().Format("2006-01-02"), num)
_, err = os.Lstat(fname) _, err = os.Lstat(fname)
} }
// return error if the last file checked still existed // return error if the last file checked still existed
if err == nil { if err == nil {
return fmt.Errorf("Rotate: Cannot find free log number to rename %s\n", w.filename) return fmt.Errorf("Rotate: Cannot find free log number to rename %s\n", w.Filename)
} }
// block Logger's io.Writer // block Logger's io.Writer
@ -204,7 +183,7 @@ func (w *FileLogWriter) DoRotate() error {
// close fd before rename // close fd before rename
// Rename the file to its newfound home // Rename the file to its newfound home
err = os.Rename(w.filename, fname) err = os.Rename(w.Filename, fname)
if err != nil { if err != nil {
return fmt.Errorf("Rotate: %s\n", err) return fmt.Errorf("Rotate: %s\n", err)
} }
@ -222,10 +201,10 @@ func (w *FileLogWriter) DoRotate() error {
} }
func (w *FileLogWriter) deleteOldLog() { func (w *FileLogWriter) deleteOldLog() {
dir := path.Dir(w.filename) dir := path.Dir(w.Filename)
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() && info.ModTime().Unix() < (time.Now().Unix()-60*60*24*w.maxdays) { if !info.IsDir() && info.ModTime().Unix() < (time.Now().Unix()-60*60*24*w.Maxdays) {
if strings.HasPrefix(filepath.Base(path), filepath.Base(w.filename)) { if strings.HasPrefix(filepath.Base(path), filepath.Base(w.Filename)) {
os.Remove(path) os.Remove(path)
} }
} }

View File

@ -2,7 +2,6 @@ package logs
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"net/smtp" "net/smtp"
"strings" "strings"
@ -15,77 +14,51 @@ const (
// smtpWriter is used to send emails via given SMTP-server. // smtpWriter is used to send emails via given SMTP-server.
type SmtpWriter struct { type SmtpWriter struct {
username string Username string `json:"Username"`
password string Password string `json:"password"`
host string Host string `json:"Host"`
subject string Subject string `json:"subject"`
recipientAddresses []string RecipientAddresses []string `json:"sendTos"`
level int Level int `json:"level"`
} }
func NewSmtpWriter() LoggerInterface { func NewSmtpWriter() LoggerInterface {
return &SmtpWriter{level: LevelTrace} return &SmtpWriter{Level: LevelTrace}
} }
func (s *SmtpWriter) Init(jsonconfig string) error { func (s *SmtpWriter) Init(jsonconfig string) error {
var m map[string]interface{} err := json.Unmarshal([]byte(jsonconfig), s)
err := json.Unmarshal([]byte(jsonconfig), &m)
if err != nil { if err != nil {
return err return err
} }
if username, ok := m["username"]; !ok {
return errors.New("smtp config must have auth username")
} else if password, ok := m["password"]; !ok {
return errors.New("smtp config must have auth password")
} else if hostname, ok := m["host"]; !ok {
return errors.New("smtp config must have host like 'mail.example.com:25'")
} else if sendTos, ok := m["sendTos"]; !ok {
return errors.New("smtp config must have sendTos")
} else {
s.username = username.(string)
s.password = password.(string)
s.host = hostname.(string)
for _, v := range sendTos.([]interface{}) {
s.recipientAddresses = append(s.recipientAddresses, v.(string))
}
}
if subject, ok := m["subject"]; ok {
s.subject = subject.(string)
} else {
s.subject = subjectPhrase
}
if lv, ok := m["level"]; ok {
s.level = int(lv.(float64))
}
return nil return nil
} }
func (s *SmtpWriter) WriteMsg(msg string, level int) error { func (s *SmtpWriter) WriteMsg(msg string, level int) error {
if level < s.level { if level < s.Level {
return nil return nil
} }
hp := strings.Split(s.host, ":") hp := strings.Split(s.Host, ":")
// Set up authentication information. // Set up authentication information.
auth := smtp.PlainAuth( auth := smtp.PlainAuth(
"", "",
s.username, s.Username,
s.password, s.Password,
hp[0], hp[0],
) )
// Connect to the server, authenticate, set the sender and recipient, // Connect to the server, authenticate, set the sender and recipient,
// and send the email all in one step. // and send the email all in one step.
content_type := "Content-Type: text/plain" + "; charset=UTF-8" content_type := "Content-Type: text/plain" + "; charset=UTF-8"
mailmsg := []byte("To: " + strings.Join(s.recipientAddresses, ";") + "\r\nFrom: " + s.username + "<" + s.username + mailmsg := []byte("To: " + strings.Join(s.RecipientAddresses, ";") + "\r\nFrom: " + s.Username + "<" + s.Username +
">\r\nSubject: " + s.subject + "\r\n" + content_type + "\r\n\r\n" + fmt.Sprintf(".%s", time.Now().Format("2006-01-02 15:04:05")) + msg) ">\r\nSubject: " + s.Subject + "\r\n" + content_type + "\r\n\r\n" + fmt.Sprintf(".%s", time.Now().Format("2006-01-02 15:04:05")) + msg)
err := smtp.SendMail( err := smtp.SendMail(
s.host, s.Host,
auth, auth,
s.username, s.Username,
s.recipientAddresses, s.RecipientAddresses,
mailmsg, mailmsg,
) )