golint fixed for modules/log

This commit is contained in:
Lunny Xiao 2016-11-26 19:53:29 +08:00
parent 0a76d260fa
commit 3228544c31
5 changed files with 86 additions and 56 deletions

View file

@ -23,20 +23,20 @@ type ConnWriter struct {
Level int `json:"level"`
}
// create new ConnWrite returning as LoggerInterface.
// NewConn creates new ConnWrite returning as LoggerInterface.
func NewConn() LoggerInterface {
conn := new(ConnWriter)
conn.Level = TRACE
return conn
}
// init connection writer with json config.
// Init inits connection writer with json config.
// json config only need key "level".
func (cw *ConnWriter) Init(jsonconfig string) error {
return json.Unmarshal([]byte(jsonconfig), cw)
}
// write message in connection.
// WriteMsg writes message in connection.
// if connection is down, try to re-connect.
func (cw *ConnWriter) WriteMsg(msg string, skip, level int) error {
if cw.Level > level {
@ -55,10 +55,11 @@ func (cw *ConnWriter) WriteMsg(msg string, skip, level int) error {
return nil
}
func (_ *ConnWriter) Flush() {
// Flush no things for this implementation
func (cw *ConnWriter) Flush() {
}
// destroy connection writer and close tcp listener.
// Destroy destroy connection writer and close tcp listener.
func (cw *ConnWriter) Destroy() {
if cw.innerWriter == nil {
return

View file

@ -11,8 +11,10 @@ import (
"runtime"
)
// Brush brush type
type Brush func(string) string
// NewBrush create a brush according color
func NewBrush(color string) Brush {
pre := "\033["
reset := "\033[0m"
@ -37,7 +39,7 @@ type ConsoleWriter struct {
Level int `json:"level"`
}
// create ConsoleWriter returning as LoggerInterface.
// NewConsole create ConsoleWriter returning as LoggerInterface.
func NewConsole() LoggerInterface {
return &ConsoleWriter{
lg: log.New(os.Stdout, "", log.Ldate|log.Ltime),
@ -45,10 +47,14 @@ func NewConsole() LoggerInterface {
}
}
// Init inits connection writer with json config.
// json config only need key "level".
func (cw *ConsoleWriter) Init(config string) error {
return json.Unmarshal([]byte(config), cw)
}
// WriteMsg writes message in console.
// if OS is windows, ignore colors.
func (cw *ConsoleWriter) WriteMsg(msg string, skip, level int) error {
if cw.Level > level {
return nil
@ -61,11 +67,12 @@ func (cw *ConsoleWriter) WriteMsg(msg string, skip, level int) error {
return nil
}
func (_ *ConsoleWriter) Flush() {
// Flush when log should be flushed
func (cw *ConsoleWriter) Flush() {
}
func (_ *ConsoleWriter) Destroy() {
// Destroy when writer is destroy
func (cw *ConsoleWriter) Destroy() {
}
func init() {

View file

@ -25,17 +25,17 @@ type FileLogWriter struct {
// The opened file
Filename string `json:"filename"`
Maxlines int `json:"maxlines"`
maxlines_curlines int
Maxlines int `json:"maxlines"`
maxlinesCurlines int
// Rotate at size
Maxsize int `json:"maxsize"`
maxsize_cursize int
Maxsize int `json:"maxsize"`
maxsizeCursize int
// Rotate daily
Daily bool `json:"daily"`
Maxdays int64 `json:"maxdays"`
daily_opendate int
Daily bool `json:"daily"`
Maxdays int64 `json:"maxdays"`
dailyOpenDate int
Rotate bool `json:"rotate"`
@ -44,20 +44,20 @@ type FileLogWriter struct {
Level int `json:"level"`
}
// an *os.File writer with locker.
// MuxWriter an *os.File writer with locker.
type MuxWriter struct {
sync.Mutex
fd *os.File
}
// write to os.File.
// Write writes to os.File.
func (l *MuxWriter) Write(b []byte) (int, error) {
l.Lock()
defer l.Unlock()
return l.fd.Write(b)
}
// set os.File in writer.
// SetFd sets os.File in writer.
func (l *MuxWriter) SetFd(fd *os.File) {
if l.fd != nil {
l.fd.Close()
@ -65,7 +65,7 @@ func (l *MuxWriter) SetFd(fd *os.File) {
l.fd = fd
}
// create a FileLogWriter returning as LoggerInterface.
// NewFileWriter create a FileLogWriter returning as LoggerInterface.
func NewFileWriter() LoggerInterface {
w := &FileLogWriter{
Filename: "",
@ -103,7 +103,7 @@ func (w *FileLogWriter) Init(config string) error {
return w.StartLogger()
}
// start file logger. create log file and set to locker-inside file writer.
// StartLogger start file logger. create log file and set to locker-inside file writer.
func (w *FileLogWriter) StartLogger() error {
fd, err := w.createLogFile()
if err != nil {
@ -119,19 +119,19 @@ func (w *FileLogWriter) StartLogger() error {
func (w *FileLogWriter) docheck(size int) {
w.startLock.Lock()
defer w.startLock.Unlock()
if w.Rotate && ((w.Maxlines > 0 && w.maxlines_curlines >= w.Maxlines) ||
(w.Maxsize > 0 && w.maxsize_cursize >= w.Maxsize) ||
(w.Daily && time.Now().Day() != w.daily_opendate)) {
if w.Rotate && ((w.Maxlines > 0 && w.maxlinesCurlines >= w.Maxlines) ||
(w.Maxsize > 0 && w.maxsizeCursize >= w.Maxsize) ||
(w.Daily && time.Now().Day() != w.dailyOpenDate)) {
if err := w.DoRotate(); err != nil {
fmt.Fprintf(os.Stderr, "FileLogWriter(%q): %s\n", w.Filename, err)
return
}
}
w.maxlines_curlines++
w.maxsize_cursize += size
w.maxlinesCurlines++
w.maxsizeCursize += size
}
// write logger message into file.
// WriteMsg writes logger message into file.
func (w *FileLogWriter) WriteMsg(msg string, skip, level int) error {
if level < w.Level {
return nil
@ -151,18 +151,18 @@ func (w *FileLogWriter) initFd() error {
fd := w.mw.fd
finfo, err := fd.Stat()
if err != nil {
return fmt.Errorf("get stat: %s\n", err)
return fmt.Errorf("get stat: %s", err)
}
w.maxsize_cursize = int(finfo.Size())
w.daily_opendate = time.Now().Day()
w.maxsizeCursize = int(finfo.Size())
w.dailyOpenDate = time.Now().Day()
if finfo.Size() > 0 {
content, err := ioutil.ReadFile(w.Filename)
if err != nil {
return err
}
w.maxlines_curlines = len(strings.Split(string(content), "\n"))
w.maxlinesCurlines = len(strings.Split(string(content), "\n"))
} else {
w.maxlines_curlines = 0
w.maxlinesCurlines = 0
}
return nil
}
@ -181,7 +181,7 @@ func (w *FileLogWriter) DoRotate() error {
}
// return error if the last file checked still existed
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", w.Filename)
}
// block Logger's io.Writer
@ -194,12 +194,12 @@ func (w *FileLogWriter) DoRotate() error {
// close fd before rename
// Rename the file to its newfound home
if err = os.Rename(w.Filename, fname); err != nil {
return fmt.Errorf("Rotate: %s\n", err)
return fmt.Errorf("Rotate: %s", err)
}
// re-start logger
if err = w.StartLogger(); err != nil {
return fmt.Errorf("Rotate StartLogger: %s\n", err)
return fmt.Errorf("Rotate StartLogger: %s", err)
}
go w.deleteOldLog()
@ -226,12 +226,12 @@ func (w *FileLogWriter) deleteOldLog() {
})
}
// destroy file logger, close file writer.
// Destroy destroy file logger, close file writer.
func (w *FileLogWriter) Destroy() {
w.mw.fd.Close()
}
// flush file logger.
// Flush flush file logger.
// there are no buffering messages in file logger in memory.
// flush file means sync file from disk.
func (w *FileLogWriter) Flush() {

View file

@ -15,10 +15,12 @@ import (
)
var (
loggers []*Logger
loggers []*Logger
// GitLogger logger for git
GitLogger *Logger
)
// NewLogger create a logger
func NewLogger(bufLen int64, mode, config string) {
logger := newLogger(bufLen)
@ -37,6 +39,7 @@ func NewLogger(bufLen int64, mode, config string) {
}
}
// NewGitLogger create a logger for git
// FIXME: use same log level as other loggers.
func NewGitLogger(logPath string) {
os.MkdirAll(path.Dir(logPath), os.ModePerm)
@ -44,42 +47,49 @@ func NewGitLogger(logPath string) {
GitLogger.SetLogger("file", fmt.Sprintf(`{"level":0,"filename":"%s","rotate":false}`, logPath))
}
// Trace records trace log
func Trace(format string, v ...interface{}) {
for _, logger := range loggers {
logger.Trace(format, v...)
}
}
// Debug records debug log
func Debug(format string, v ...interface{}) {
for _, logger := range loggers {
logger.Debug(format, v...)
}
}
// Info records info log
func Info(format string, v ...interface{}) {
for _, logger := range loggers {
logger.Info(format, v...)
}
}
// Warn records warnning log
func Warn(format string, v ...interface{}) {
for _, logger := range loggers {
logger.Warn(format, v...)
}
}
// Error records error log
func Error(skip int, format string, v ...interface{}) {
for _, logger := range loggers {
logger.Error(skip, format, v...)
}
}
// Critical records critical log
func Critical(skip int, format string, v ...interface{}) {
for _, logger := range loggers {
logger.Critical(skip, format, v...)
}
}
// Fatal records error log and exit process
func Fatal(skip int, format string, v ...interface{}) {
Error(skip, format, v...)
for _, l := range loggers {
@ -88,6 +98,7 @@ func Fatal(skip int, format string, v ...interface{}) {
os.Exit(1)
}
// Close closes all the loggers
func Close() {
for _, l := range loggers {
l.Close()
@ -101,8 +112,10 @@ func Close() {
// |___|___| /__| \___ >__| |__| (____ /\___ >___ >
// \/ \/ \/ \/ \/
type LogLevel int
// LogLevel level type for log
//type LogLevel int
// log levels
const (
TRACE = iota
DEBUG
@ -274,36 +287,43 @@ func (l *Logger) Close() {
}
}
// Trace records trace log
func (l *Logger) Trace(format string, v ...interface{}) {
msg := fmt.Sprintf("[T] "+format, v...)
l.writerMsg(0, TRACE, msg)
}
// Debug records debug log
func (l *Logger) Debug(format string, v ...interface{}) {
msg := fmt.Sprintf("[D] "+format, v...)
l.writerMsg(0, DEBUG, msg)
}
// Info records information log
func (l *Logger) Info(format string, v ...interface{}) {
msg := fmt.Sprintf("[I] "+format, v...)
l.writerMsg(0, INFO, msg)
}
// Warn records warnning log
func (l *Logger) Warn(format string, v ...interface{}) {
msg := fmt.Sprintf("[W] "+format, v...)
l.writerMsg(0, WARN, msg)
}
// Error records error log
func (l *Logger) Error(skip int, format string, v ...interface{}) {
msg := fmt.Sprintf("[E] "+format, v...)
l.writerMsg(skip, ERROR, msg)
}
// Critical records critical log
func (l *Logger) Critical(skip int, format string, v ...interface{}) {
msg := fmt.Sprintf("[C] "+format, v...)
l.writerMsg(skip, CRITICAL, msg)
}
// Fatal records error log and exit the process
func (l *Logger) Fatal(skip int, format string, v ...interface{}) {
msg := fmt.Sprintf("[F] "+format, v...)
l.writerMsg(skip, FATAL, msg)

View file

@ -16,7 +16,7 @@ const (
subjectPhrase = "Diagnostic message from server"
)
// smtpWriter implements LoggerInterface and is used to send emails via given SMTP-server.
// SMTPWriter implements LoggerInterface and is used to send emails via given SMTP-server.
type SMTPWriter struct {
Username string `json:"Username"`
Password string `json:"password"`
@ -26,12 +26,12 @@ type SMTPWriter struct {
Level int `json:"level"`
}
// create smtp writer.
// NewSMTPWriter creates smtp writer.
func NewSMTPWriter() LoggerInterface {
return &SMTPWriter{Level: TRACE}
}
// init smtp writer with json config.
// Init smtp writer with json config.
// config like:
// {
// "Username":"example@gmail.com",
@ -45,41 +45,43 @@ func (sw *SMTPWriter) Init(jsonconfig string) error {
return json.Unmarshal([]byte(jsonconfig), sw)
}
// write message in smtp writer.
// WriteMsg writes message in smtp writer.
// it will send an email with subject and only this message.
func (s *SMTPWriter) WriteMsg(msg string, skip, level int) error {
if level < s.Level {
func (sw *SMTPWriter) WriteMsg(msg string, skip, level int) error {
if level < sw.Level {
return nil
}
hp := strings.Split(s.Host, ":")
hp := strings.Split(sw.Host, ":")
// Set up authentication information.
auth := smtp.PlainAuth(
"",
s.Username,
s.Password,
sw.Username,
sw.Password,
hp[0],
)
// Connect to the server, authenticate, set the sender and recipient,
// and send the email all in one step.
content_type := "Content-Type: text/plain" + "; charset=UTF-8"
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)
contentType := "Content-Type: text/plain" + "; charset=UTF-8"
mailmsg := []byte("To: " + strings.Join(sw.RecipientAddresses, ";") + "\r\nFrom: " + sw.Username + "<" + sw.Username +
">\r\nSubject: " + sw.Subject + "\r\n" + contentType + "\r\n\r\n" + fmt.Sprintf(".%s", time.Now().Format("2006-01-02 15:04:05")) + msg)
return smtp.SendMail(
s.Host,
sw.Host,
auth,
s.Username,
s.RecipientAddresses,
sw.Username,
sw.RecipientAddresses,
mailmsg,
)
}
func (_ *SMTPWriter) Flush() {
// Flush when log should be flushed
func (sw *SMTPWriter) Flush() {
}
func (_ *SMTPWriter) Destroy() {
// Destroy when writer is destroy
func (sw *SMTPWriter) Destroy() {
}
func init() {