Merge pull request #269 from lunny/lunny/golint_modules_log

Golint fixed for modules/log
tokarchuk/v1.17
Thomas Boerger 8 years ago committed by GitHub
commit 7a92519bd7
  1. 11
      modules/log/conn.go
  2. 15
      modules/log/console.go
  3. 56
      modules/log/file.go
  4. 24
      modules/log/log.go
  5. 36
      modules/log/smtp.go

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

@ -11,8 +11,10 @@ import (
"runtime" "runtime"
) )
// Brush brush type
type Brush func(string) string type Brush func(string) string
// NewBrush create a brush according color
func NewBrush(color string) Brush { func NewBrush(color string) Brush {
pre := "\033[" pre := "\033["
reset := "\033[0m" reset := "\033[0m"
@ -37,7 +39,7 @@ type ConsoleWriter struct {
Level int `json:"level"` Level int `json:"level"`
} }
// create ConsoleWriter returning as LoggerInterface. // NewConsole create ConsoleWriter returning as LoggerInterface.
func NewConsole() LoggerInterface { func NewConsole() LoggerInterface {
return &ConsoleWriter{ return &ConsoleWriter{
lg: log.New(os.Stdout, "", log.Ldate|log.Ltime), 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 { func (cw *ConsoleWriter) Init(config string) error {
return json.Unmarshal([]byte(config), cw) 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 { func (cw *ConsoleWriter) WriteMsg(msg string, skip, level int) error {
if cw.Level > level { if cw.Level > level {
return nil return nil
@ -61,11 +67,12 @@ func (cw *ConsoleWriter) WriteMsg(msg string, skip, level int) error {
return nil 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() { func init() {

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

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

@ -16,7 +16,7 @@ const (
subjectPhrase = "Diagnostic message from server" 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 { type SMTPWriter struct {
Username string `json:"Username"` Username string `json:"Username"`
Password string `json:"password"` Password string `json:"password"`
@ -26,12 +26,12 @@ type SMTPWriter struct {
Level int `json:"level"` Level int `json:"level"`
} }
// create smtp writer. // NewSMTPWriter creates smtp writer.
func NewSMTPWriter() LoggerInterface { func NewSMTPWriter() LoggerInterface {
return &SMTPWriter{Level: TRACE} return &SMTPWriter{Level: TRACE}
} }
// init smtp writer with json config. // Init smtp writer with json config.
// config like: // config like:
// { // {
// "Username":"example@gmail.com", // "Username":"example@gmail.com",
@ -45,41 +45,43 @@ func (sw *SMTPWriter) Init(jsonconfig string) error {
return json.Unmarshal([]byte(jsonconfig), sw) 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. // it will send an email with subject and only this message.
func (s *SMTPWriter) WriteMsg(msg string, skip, level int) error { func (sw *SMTPWriter) WriteMsg(msg string, skip, level int) error {
if level < s.Level { if level < sw.Level {
return nil return nil
} }
hp := strings.Split(s.Host, ":") hp := strings.Split(sw.Host, ":")
// Set up authentication information. // Set up authentication information.
auth := smtp.PlainAuth( auth := smtp.PlainAuth(
"", "",
s.Username, sw.Username,
s.Password, sw.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" contentType := "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(sw.RecipientAddresses, ";") + "\r\nFrom: " + sw.Username + "<" + sw.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: " + 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( return smtp.SendMail(
s.Host, sw.Host,
auth, auth,
s.Username, sw.Username,
s.RecipientAddresses, sw.RecipientAddresses,
mailmsg, 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() { func init() {

Loading…
Cancel
Save