包名:mylog
main.go
package mylog
// DEBUG TRACE INFO WARN ERROR CRITICAL
const (
DEBUG = iota
TRACE
INFO
WARN
ERROR
CRITICAL
)
// level:0->DEBUG;1->TRACE... also: e.g:mylog.DEBUG...
func MyLog(level int, logFilePath string, logFileName string, format string, args ...interface{}) {
f := newFileLogger(level, logFilePath, logFileName)
f.record_info(level, format, args)
}
file_log.go
package mylog
import (
"fmt"
"os"
"time"
)
// FileLogger往文件中记录日志的结构体
type fileLogger struct {
level int
logFilePath string
logFileName string
logFile *os.File
}
// NewFileLogger 生成文件日志结构体示例的构造函数
func newFileLogger(level int, logFilePath string, logFileName string) *fileLogger {
flobj := &fileLogger{
level: level,
logFilePath: logFilePath,
logFileName: logFileName,
}
flobj.initFileLogger()
return flobj
}
// 初始化文件日志的文件句柄
func (f *fileLogger) initFileLogger() {
filepath := fmt.Sprintf("%s%s", f.logFilePath, f.logFileName)
file, err := os.OpenFile(filepath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
//defer file.Close()
if err != nil {
panic(fmt.Sprintf("open file:%s failed", filepath))
}
f.logFile = file
}
// 拼接日志信息并记录
func (f *fileLogger) record_info(level int, format string, args ...interface{}) {
o_time := time.Now()
rec_time := o_time.Format(" [2006-01-02 15:04:05] ")
var inf string
switch level {
case 0:
inf = fmt.Sprintf(" [DEBUG]%s%s\n", rec_time, format)
case 1:
inf = fmt.Sprintf(" [TRACE]%s%s\n", rec_time, format)
case 2:
inf = fmt.Sprintf(" [INFO]%s%s\n", rec_time, format)
case 3:
inf = fmt.Sprintf(" [WARN]%s%s\n", rec_time, format)
case 4:
inf = fmt.Sprintf(" [ERROR]%s%s\n", rec_time, format)
case 5:
inf = fmt.Sprintf(" [CRITICAL]%s%s\n", rec_time, format)
default:
panic(fmt.Sprintf("logtype error:wrong num, required 1~5 but given %d", level))
}
format = inf
fmt.Fprintf(f.logFile, format, args...)
}
调用测试
package main
import (
"log_demo/mylog"
)
func main(){
mylog.MyLog(3,"./","test.log","%d的用户正在登陆",1)
}
有疑问加站长微信联系(非本文作者)