1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-25 21:11:29 +00:00

golint logs

This commit is contained in:
astaxie 2015-09-11 23:08:24 +08:00
parent 657995092a
commit 34877c52a9
6 changed files with 129 additions and 128 deletions

View File

@ -21,9 +21,9 @@ import (
"net"
)
// ConnWriter implements LoggerInterface.
// connWriter implements LoggerInterface.
// it writes messages in keep-live tcp connection.
type ConnWriter struct {
type connWriter struct {
lg *log.Logger
innerWriter io.WriteCloser
ReconnectOnMsg bool `json:"reconnectOnMsg"`
@ -33,22 +33,22 @@ type ConnWriter struct {
Level int `json:"level"`
}
// create new ConnWrite returning as LoggerInterface.
func NewConn() LoggerInterface {
conn := new(ConnWriter)
// NewConn create new ConnWrite returning as LoggerInterface.
func NewConn() Logger {
conn := new(connWriter)
conn.Level = LevelTrace
return conn
}
// init connection writer with json config.
// Init init connection writer with json config.
// json config only need key "level".
func (c *ConnWriter) Init(jsonconfig string) error {
func (c *connWriter) Init(jsonconfig string) error {
return json.Unmarshal([]byte(jsonconfig), c)
}
// write message in connection.
// WriteMsg write message in connection.
// if connection is down, try to re-connect.
func (c *ConnWriter) WriteMsg(msg string, level int) error {
func (c *connWriter) WriteMsg(msg string, level int) error {
if level > c.Level {
return nil
}
@ -66,19 +66,19 @@ func (c *ConnWriter) WriteMsg(msg string, level int) error {
return nil
}
// implementing method. empty.
func (c *ConnWriter) Flush() {
// Flush implementing method. empty.
func (c *connWriter) Flush() {
}
// destroy connection writer and close tcp listener.
func (c *ConnWriter) Destroy() {
// Destroy destroy connection writer and close tcp listener.
func (c *connWriter) Destroy() {
if c.innerWriter != nil {
c.innerWriter.Close()
}
}
func (c *ConnWriter) connect() error {
func (c *connWriter) connect() error {
if c.innerWriter != nil {
c.innerWriter.Close()
c.innerWriter = nil
@ -98,7 +98,7 @@ func (c *ConnWriter) connect() error {
return nil
}
func (c *ConnWriter) neddedConnectOnMsg() bool {
func (c *connWriter) neddedConnectOnMsg() bool {
if c.Reconnect {
c.Reconnect = false
return true

View File

@ -21,9 +21,11 @@ import (
"runtime"
)
type Brush func(string) string
// brush is a color join function
type brush func(string) string
func NewBrush(color string) Brush {
// newBrush return a fix color Brush
func newBrush(color string) brush {
pre := "\033["
reset := "\033[0m"
return func(text string) string {
@ -31,43 +33,43 @@ func NewBrush(color string) Brush {
}
}
var colors = []Brush{
NewBrush("1;37"), // Emergency white
NewBrush("1;36"), // Alert cyan
NewBrush("1;35"), // Critical magenta
NewBrush("1;31"), // Error red
NewBrush("1;33"), // Warning yellow
NewBrush("1;32"), // Notice green
NewBrush("1;34"), // Informational blue
NewBrush("1;34"), // Debug blue
var colors = []brush{
newBrush("1;37"), // Emergency white
newBrush("1;36"), // Alert cyan
newBrush("1;35"), // Critical magenta
newBrush("1;31"), // Error red
newBrush("1;33"), // Warning yellow
newBrush("1;32"), // Notice green
newBrush("1;34"), // Informational blue
newBrush("1;34"), // Debug blue
}
// ConsoleWriter implements LoggerInterface and writes messages to terminal.
type ConsoleWriter struct {
// consoleWriter implements LoggerInterface and writes messages to terminal.
type consoleWriter struct {
lg *log.Logger
Level int `json:"level"`
}
// create ConsoleWriter returning as LoggerInterface.
func NewConsole() LoggerInterface {
cw := &ConsoleWriter{
// NewConsole create ConsoleWriter returning as LoggerInterface.
func NewConsole() Logger {
cw := &consoleWriter{
lg: log.New(os.Stdout, "", log.Ldate|log.Ltime),
Level: LevelDebug,
}
return cw
}
// init console logger.
// Init init console logger.
// jsonconfig like '{"level":LevelTrace}'.
func (c *ConsoleWriter) Init(jsonconfig string) error {
func (c *consoleWriter) Init(jsonconfig string) error {
if len(jsonconfig) == 0 {
return nil
}
return json.Unmarshal([]byte(jsonconfig), c)
}
// write message in console.
func (c *ConsoleWriter) WriteMsg(msg string, level int) error {
// WriteMsg write message in console.
func (c *consoleWriter) WriteMsg(msg string, level int) error {
if level > c.Level {
return nil
}
@ -80,13 +82,13 @@ func (c *ConsoleWriter) WriteMsg(msg string, level int) error {
return nil
}
// implementing method. empty.
func (c *ConsoleWriter) Destroy() {
// Destroy implementing method. empty.
func (c *consoleWriter) Destroy() {
}
// implementing method. empty.
func (c *ConsoleWriter) Flush() {
// Flush implementing method. empty.
func (c *consoleWriter) Flush() {
}

View File

@ -12,7 +12,8 @@ import (
"github.com/belogik/goes"
)
func NewES() logs.LoggerInterface {
// NewES return a LoggerInterface
func NewES() logs.Logger {
cw := &esLogger{
Level: logs.LevelDebug,
}
@ -46,6 +47,7 @@ func (el *esLogger) Init(jsonconfig string) error {
return nil
}
// WriteMsg will write the msg and level into es
func (el *esLogger) WriteMsg(msg string, level int) error {
if level > el.Level {
return nil
@ -63,10 +65,12 @@ func (el *esLogger) WriteMsg(msg string, level int) error {
return err
}
// Destroy is a empty method
func (el *esLogger) Destroy() {
}
// Flush is a empty method
func (el *esLogger) Flush() {
}

View File

@ -28,25 +28,25 @@ import (
"time"
)
// FileLogWriter implements LoggerInterface.
// fileLogWriter implements LoggerInterface.
// It writes messages by lines limit, file size limit, or time frequency.
type FileLogWriter struct {
type fileLogWriter struct {
*log.Logger
mw *MuxWriter
// 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"`
@ -55,7 +55,7 @@ type FileLogWriter struct {
Level int `json:"level"`
}
// an *os.File writer with locker.
// MuxWriter is an *os.File writer with locker.
type MuxWriter struct {
sync.Mutex
fd *os.File
@ -68,7 +68,7 @@ func (l *MuxWriter) Write(b []byte) (int, error) {
return l.fd.Write(b)
}
// set os.File in writer.
// SetFd set os.File in writer.
func (l *MuxWriter) SetFd(fd *os.File) {
if l.fd != nil {
l.fd.Close()
@ -76,9 +76,9 @@ func (l *MuxWriter) SetFd(fd *os.File) {
l.fd = fd
}
// create a FileLogWriter returning as LoggerInterface.
func NewFileWriter() LoggerInterface {
w := &FileLogWriter{
// NewFileWriter create a FileLogWriter returning as LoggerInterface.
func newFileWriter() Logger {
w := &fileLogWriter{
Filename: "",
Maxlines: 1000000,
Maxsize: 1 << 28, //256 MB
@ -104,7 +104,7 @@ func NewFileWriter() LoggerInterface {
// "maxdays":15,
// "rotate":true
// }
func (w *FileLogWriter) Init(jsonconfig string) error {
func (w *fileLogWriter) Init(jsonconfig string) error {
err := json.Unmarshal([]byte(jsonconfig), w)
if err != nil {
return err
@ -117,7 +117,7 @@ func (w *FileLogWriter) Init(jsonconfig string) error {
}
// 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()
if err != nil {
return err
@ -126,23 +126,23 @@ func (w *FileLogWriter) startLogger() error {
return w.initFd()
}
func (w *FileLogWriter) docheck(size int) {
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.
func (w *FileLogWriter) WriteMsg(msg string, level int) error {
// WriteMsg write logger message into file.
func (w *fileLogWriter) WriteMsg(msg string, level int) error {
if level > w.Level {
return nil
}
@ -152,32 +152,32 @@ func (w *FileLogWriter) WriteMsg(msg string, level int) error {
return nil
}
func (w *FileLogWriter) createLogFile() (*os.File, error) {
func (w *fileLogWriter) createLogFile() (*os.File, error) {
// Open the log file
fd, err := os.OpenFile(w.Filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)
return fd, err
}
func (w *FileLogWriter) initFd() error {
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()
w.maxlines_curlines = 0
w.maxsizeCursize = int(finfo.Size())
w.dailyOpendate = time.Now().Day()
w.maxlinesCurlines = 0
if finfo.Size() > 0 {
count, err := w.lines()
if err != nil {
return err
}
w.maxlines_curlines = count
w.maxlinesCurlines = count
}
return nil
}
func (w *FileLogWriter) lines() (int, error) {
func (w *fileLogWriter) lines() (int, error) {
fd, err := os.Open(w.Filename)
if err != nil {
return 0, err
@ -206,7 +206,7 @@ func (w *FileLogWriter) lines() (int, error) {
// DoRotate means it need to write file in new file.
// new file name like xx.2013-01-01.2.log
func (w *FileLogWriter) DoRotate() error {
func (w *fileLogWriter) DoRotate() error {
_, err := os.Lstat(w.Filename)
if err == nil { // file exists
// Find the next available number
@ -252,7 +252,7 @@ func (w *FileLogWriter) DoRotate() error {
return nil
}
func (w *FileLogWriter) deleteOldLog() {
func (w *fileLogWriter) deleteOldLog() {
dir := filepath.Dir(w.Filename)
filepath.Walk(dir, func(path string, info os.FileInfo, err error) (returnErr error) {
defer func() {
@ -271,18 +271,18 @@ func (w *FileLogWriter) deleteOldLog() {
})
}
// destroy file logger, close file writer.
func (w *FileLogWriter) Destroy() {
// Destroy close the file desciption, 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() {
func (w *fileLogWriter) Flush() {
w.mw.fd.Sync()
}
func init() {
Register("file", NewFileWriter)
Register("file", newFileWriter)
}

View File

@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
// Package logs provide a general log interface
// Usage:
//
// import "github.com/astaxie/beego/logs"
@ -60,10 +61,10 @@ const (
LevelWarn = LevelWarning
)
type loggerType func() LoggerInterface
type loggerType func() Logger
// LoggerInterface defines the behavior of a log provider.
type LoggerInterface interface {
// Logger defines the behavior of a log provider.
type Logger interface {
Init(config string) error
WriteMsg(msg string, level int) error
Destroy()
@ -94,7 +95,7 @@ type BeeLogger struct {
loggerFuncCallDepth int
asynchronous bool
msg chan *logMsg
outputs map[string]LoggerInterface
outputs map[string]Logger
}
type logMsg struct {
@ -110,10 +111,11 @@ func NewLogger(channellen int64) *BeeLogger {
bl.level = LevelDebug
bl.loggerFuncCallDepth = 2
bl.msg = make(chan *logMsg, channellen)
bl.outputs = make(map[string]LoggerInterface)
bl.outputs = make(map[string]Logger)
return bl
}
// Async set the log to asynchronous and start the goroutine
func (bl *BeeLogger) Async() *BeeLogger {
bl.asynchronous = true
go bl.startLogger()
@ -139,7 +141,7 @@ func (bl *BeeLogger) SetLogger(adaptername string, config string) error {
return nil
}
// remove a logger adapter in BeeLogger.
// DelLogger remove a logger adapter in BeeLogger.
func (bl *BeeLogger) DelLogger(adaptername string) error {
bl.lock.Lock()
defer bl.lock.Unlock()
@ -147,9 +149,8 @@ func (bl *BeeLogger) DelLogger(adaptername string) error {
lg.Destroy()
delete(bl.outputs, adaptername)
return nil
} else {
return fmt.Errorf("logs: unknown adaptername %q (forgotten Register?)", adaptername)
}
return fmt.Errorf("logs: unknown adaptername %q (forgotten Register?)", adaptername)
}
func (bl *BeeLogger) writerMsg(loglevel int, msg string) error {
@ -180,25 +181,24 @@ func (bl *BeeLogger) writerMsg(loglevel int, msg string) error {
return nil
}
// Set log message level.
//
// SetLevel Set log message level.
// If message level (such as LevelDebug) is higher than logger level (such as LevelWarning),
// log providers will not even be sent the message.
func (bl *BeeLogger) SetLevel(l int) {
bl.level = l
}
// set log funcCallDepth
// SetLogFuncCallDepth set log funcCallDepth
func (bl *BeeLogger) SetLogFuncCallDepth(d int) {
bl.loggerFuncCallDepth = d
}
// get log funcCallDepth for wrapper
// GetLogFuncCallDepth return log funcCallDepth for wrapper
func (bl *BeeLogger) GetLogFuncCallDepth() int {
return bl.loggerFuncCallDepth
}
// enable log funcCallDepth
// EnableFuncCallDepth enable log funcCallDepth
func (bl *BeeLogger) EnableFuncCallDepth(b bool) {
bl.enableFuncCallDepth = b
}
@ -219,7 +219,7 @@ func (bl *BeeLogger) startLogger() {
}
}
// Log EMERGENCY level message.
// Emergency Log EMERGENCY level message.
func (bl *BeeLogger) Emergency(format string, v ...interface{}) {
if LevelEmergency > bl.level {
return
@ -228,7 +228,7 @@ func (bl *BeeLogger) Emergency(format string, v ...interface{}) {
bl.writerMsg(LevelEmergency, msg)
}
// Log ALERT level message.
// Alert Log ALERT level message.
func (bl *BeeLogger) Alert(format string, v ...interface{}) {
if LevelAlert > bl.level {
return
@ -237,7 +237,7 @@ func (bl *BeeLogger) Alert(format string, v ...interface{}) {
bl.writerMsg(LevelAlert, msg)
}
// Log CRITICAL level message.
// Critical Log CRITICAL level message.
func (bl *BeeLogger) Critical(format string, v ...interface{}) {
if LevelCritical > bl.level {
return
@ -246,7 +246,7 @@ func (bl *BeeLogger) Critical(format string, v ...interface{}) {
bl.writerMsg(LevelCritical, msg)
}
// Log ERROR level message.
// Error Log ERROR level message.
func (bl *BeeLogger) Error(format string, v ...interface{}) {
if LevelError > bl.level {
return
@ -255,7 +255,7 @@ func (bl *BeeLogger) Error(format string, v ...interface{}) {
bl.writerMsg(LevelError, msg)
}
// Log WARNING level message.
// Warning Log WARNING level message.
func (bl *BeeLogger) Warning(format string, v ...interface{}) {
if LevelWarning > bl.level {
return
@ -264,7 +264,7 @@ func (bl *BeeLogger) Warning(format string, v ...interface{}) {
bl.writerMsg(LevelWarning, msg)
}
// Log NOTICE level message.
// Notice Log NOTICE level message.
func (bl *BeeLogger) Notice(format string, v ...interface{}) {
if LevelNotice > bl.level {
return
@ -273,7 +273,7 @@ func (bl *BeeLogger) Notice(format string, v ...interface{}) {
bl.writerMsg(LevelNotice, msg)
}
// Log INFORMATIONAL level message.
// Informational Log INFORMATIONAL level message.
func (bl *BeeLogger) Informational(format string, v ...interface{}) {
if LevelInformational > bl.level {
return
@ -282,7 +282,7 @@ func (bl *BeeLogger) Informational(format string, v ...interface{}) {
bl.writerMsg(LevelInformational, msg)
}
// Log DEBUG level message.
// Debug Log DEBUG level message.
func (bl *BeeLogger) Debug(format string, v ...interface{}) {
if LevelDebug > bl.level {
return
@ -291,7 +291,7 @@ func (bl *BeeLogger) Debug(format string, v ...interface{}) {
bl.writerMsg(LevelDebug, msg)
}
// Log WARN level message.
// Warn Log WARN level message.
// compatibility alias for Warning()
func (bl *BeeLogger) Warn(format string, v ...interface{}) {
if LevelWarning > bl.level {
@ -301,7 +301,7 @@ func (bl *BeeLogger) Warn(format string, v ...interface{}) {
bl.writerMsg(LevelWarning, msg)
}
// Log INFO level message.
// Info Log INFO level message.
// compatibility alias for Informational()
func (bl *BeeLogger) Info(format string, v ...interface{}) {
if LevelInformational > bl.level {
@ -311,7 +311,7 @@ func (bl *BeeLogger) Info(format string, v ...interface{}) {
bl.writerMsg(LevelInformational, msg)
}
// Log TRACE level message.
// Trace Log TRACE level message.
// compatibility alias for Debug()
func (bl *BeeLogger) Trace(format string, v ...interface{}) {
if LevelDebug > bl.level {
@ -321,14 +321,14 @@ func (bl *BeeLogger) Trace(format string, v ...interface{}) {
bl.writerMsg(LevelDebug, msg)
}
// flush all chan data.
// Flush flush all chan data.
func (bl *BeeLogger) Flush() {
for _, l := range bl.outputs {
l.Flush()
}
}
// close logger, flush all chan data and destroy all adapters in BeeLogger.
// Close close logger, flush all chan data and destroy all adapters in BeeLogger.
func (bl *BeeLogger) Close() {
for {
if len(bl.msg) > 0 {

View File

@ -24,13 +24,8 @@ import (
"time"
)
const (
// no usage
// subjectPhrase = "Diagnostic message from server"
)
// smtpWriter implements LoggerInterface and is used to send emails via given SMTP-server.
type SmtpWriter struct {
// SMTPWriter implements LoggerInterface and is used to send emails via given SMTP-server.
type SMTPWriter struct {
Username string `json:"username"`
Password string `json:"password"`
Host string `json:"host"`
@ -40,12 +35,12 @@ type SmtpWriter struct {
Level int `json:"level"`
}
// create smtp writer.
func NewSmtpWriter() LoggerInterface {
return &SmtpWriter{Level: LevelTrace}
// NewSMTPWriter create smtp writer.
func newSMTPWriter() Logger {
return &SMTPWriter{Level: LevelTrace}
}
// init smtp writer with json config.
// Init smtp writer with json config.
// config like:
// {
// "Username":"example@gmail.com",
@ -56,7 +51,7 @@ func NewSmtpWriter() LoggerInterface {
// "sendTos":["email1","email2"],
// "level":LevelError
// }
func (s *SmtpWriter) Init(jsonconfig string) error {
func (s *SMTPWriter) Init(jsonconfig string) error {
err := json.Unmarshal([]byte(jsonconfig), s)
if err != nil {
return err
@ -64,7 +59,7 @@ func (s *SmtpWriter) Init(jsonconfig string) error {
return nil
}
func (s *SmtpWriter) GetSmtpAuth(host string) smtp.Auth {
func (s *SMTPWriter) getSMTPAuth(host string) smtp.Auth {
if len(strings.Trim(s.Username, " ")) == 0 && len(strings.Trim(s.Password, " ")) == 0 {
return nil
}
@ -76,7 +71,7 @@ func (s *SmtpWriter) GetSmtpAuth(host string) smtp.Auth {
)
}
func (s *SmtpWriter) sendMail(hostAddressWithPort string, auth smtp.Auth, fromAddress string, recipients []string, msgContent []byte) error {
func (s *SMTPWriter) sendMail(hostAddressWithPort string, auth smtp.Auth, fromAddress string, recipients []string, msgContent []byte) error {
client, err := smtp.Dial(hostAddressWithPort)
if err != nil {
return err
@ -129,9 +124,9 @@ func (s *SmtpWriter) sendMail(hostAddressWithPort string, auth smtp.Auth, fromAd
return nil
}
// write message in smtp writer.
// WriteMsg write message in smtp writer.
// it will send an email with subject and only this message.
func (s *SmtpWriter) WriteMsg(msg string, level int) error {
func (s *SMTPWriter) WriteMsg(msg string, level int) error {
if level > s.Level {
return nil
}
@ -139,27 +134,27 @@ func (s *SmtpWriter) WriteMsg(msg string, level int) error {
hp := strings.Split(s.Host, ":")
// Set up authentication information.
auth := s.GetSmtpAuth(hp[0])
auth := s.getSMTPAuth(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"
contentType := "Content-Type: text/plain" + "; charset=UTF-8"
mailmsg := []byte("To: " + strings.Join(s.RecipientAddresses, ";") + "\r\nFrom: " + s.FromAddress + "<" + s.FromAddress +
">\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" + contentType + "\r\n\r\n" + fmt.Sprintf(".%s", time.Now().Format("2006-01-02 15:04:05")) + msg)
return s.sendMail(s.Host, auth, s.FromAddress, s.RecipientAddresses, mailmsg)
}
// implementing method. empty.
func (s *SmtpWriter) Flush() {
// Flush implementing method. empty.
func (s *SMTPWriter) Flush() {
return
}
// implementing method. empty.
func (s *SmtpWriter) Destroy() {
// Destroy implementing method. empty.
func (s *SMTPWriter) Destroy() {
return
}
func init() {
Register("smtp", NewSmtpWriter)
Register("smtp", newSMTPWriter)
}