go实现日志库案例
需求分析:
日志文件切割:
- 按照文件大小切割
每次记录日志前都判断以下当前写的这个文件的大小
- 按照日期切割
最终版参考: 步骤
main.go 内容
package main
import (
"mylogger/logger"
"time"
)
// 测试自己写的日志相关的内容
func main() {
log := logger.NewLog("Warning")
for {
log.Debug("这是一条debug日志")
log.Trace("这是一条Trace日志")
log.Info("这是一条 info 日志")
log.Warning("这是一条 Warning 日志")
log.Error("这是一条 Error 日志")
log.Fatal("这是一条 Fatal 日志")
time.Sleep(time.Second)
}
}
mylogger.go 内容:
package logger
import (
"errors"
"fmt"
"path"
"runtime"
"strings"
"time"
)
//author baimeidashu.com
// 往终端写日志相关内容
type LogLevel uint16
const (
UNKONWN LogLevel = iota
DEBUG
TRACE
INFO
WARNING
ERROR
FATAL
)
func parseLogLeve(s string) (LogLevel, error) {
s = strings.ToLower(s)
fmt.Printf("%s", s)
fmt.Printf("-------------------------")
switch s {
case "debug":
return DEBUG, nil
case "trace":
return TRACE, nil
case "info":
return INFO, nil
case "warning":
return WARNING, nil
case "error":
return ERROR, nil
case "fatal":
return FATAL, nil
default:
err := errors.New("无效的日志级别")
return UNKONWN, err
}
}
// 把 int 转换为 字符串
func getLogString(lv LogLevel) string {
switch lv {
case DEBUG:
return "DEBUG"
case TRACE:
return "TRACE"
case INFO:
return "INFO"
case WARNING:
return "WARNING"
case ERROR:
return "ERROR"
case FATAL:
return "FATAL"
}
return "DEBUG"
}
// Logger 日志结构体
type Logger struct {
Level LogLevel
}
// NewLogger 构造函数
func NewLog(leverStr string) Logger {
lever, err := parseLogLeve(leverStr)
fmt.Println("s%", lever)
fmt.Println("s%", lever)
if err != nil {
panic(err)
}
return Logger{
Level: lever,
}
}
// 接收者变量 接收者类型
func (l Logger) enable(level LogLevel) bool {
return l.Level >= level
}
func log(lv LogLevel, msg string) {
now := time.Now()
funcName, fileName, lineNum := getInfo(3)
fmt.Printf("[%s] --[%s] --[%s:%s:%d]%s \n ", now.Format("2006-01-02 15:04:05"), getLogString(lv), fileName, funcName, lineNum, msg)
}
// 接收者变量 接收者类型 给 Logger 添加 方法
func (l Logger) Debug(msg string) {
if l.enable(DEBUG) {
log(DEBUG, msg)
}
}
func (l Logger) Trace(msg string) {
if l.enable(TRACE) {
log(TRACE, msg)
}
}
func (l Logger) Info(msg string) {
if l.enable(INFO) {
log(INFO, msg)
}
}
func (l Logger) Warning(msg string) {
if l.enable(WARNING) {
log(WARNING, msg)
}
}
func (l Logger) Error(msg string) {
if l.enable(ERROR) {
log(ERROR, msg)
}
}
func (l Logger) Fatal(msg string) {
if l.enable(FATAL) {
log(FATAL, msg)
}
}
func getInfo(skip int) (funcName string, fileName string, lineNumber int) {
pc, file, line, ok := runtime.Caller(skip)
if !ok {
fmt.Println("runtime.caller() failed\n")
return
}
funcName = runtime.FuncForPC(pc).Name()
fileName = path.Base(file)
funcName = strings.Split(funcName, ".")[1]
lineNumber = line
return
}
欢迎来撩 : 汇总all