【go文件日志重构】书史足自悦,安用勤与劬。这篇文章主要讲述go文件日志重构相关的知识,希望能为你提供帮助。
重定义go文件日志file.go
package loggingimport (
"fmt"
"log"
"os"
"time"
)var (
LogSavePath = "runtime/logs/"
LogSaveName = "log"
LogFileExt = "log"
TimeFormat = "20060102"
)func getLogFilePath() string {
return fmt.Sprintf("%s",LogSavePath)
}
func getLogFileFullPath() string{
prefixPath := getLogFilePath()
suffixPath := fmt.Sprintf("%s%s.%s",LogSaveName,time.Now().Format(TimeFormat),LogFileExt)
return fmt.Sprintf("%s%s",prefixPath,suffixPath)
}
func mkDir(){
dir,_:=os.Getwd()
err := os.MkdirAll(dir + "/" + getLogFilePath(),os.ModePerm)
if err != nil {
panic(err)
}
}
func openLogFile(filePath string) *os.File{
_,err := os.Stat(filePath)
switch{
case os.IsNotExist(err):
mkDir()
case os.IsPermission(err):
log.Fatalf("Permission:% v",err)}
handle, err := os.OpenFile(filePath,os.O_APPEND | os.O_CREATE | os.O_WRONLY,0644)
if err != nil {
log.Fatalf("fail to openfile :%v",err)
}
return handle}
log.go
package loggingimport (
"fmt"
"log"
"os"
"path/filepath"
"runtime"
)type Level intvar (
F *os.File
DefaultPrefix = ""
DefaultCallerDepth = 2
logger *log.Logger
logPrefix = ""
levelFlags = []string{"DEBUG","INFO","WARN","ERROR","FATAL"}
)const (
DEBUG Level = iota
INFO
WARNING
ERROR
FATAL
)func init(){
filePath := getLogFileFullPath()
F = openLogFile(filePath)
logger = log.New(F,DefaultPrefix,log.LstdFlags)
}
func Debug( v ...interface{}){
log.SetPrefix(string(DEBUG))
logger.Println(v)
}
func Info( v ...interface{}){
log.SetPrefix(string(INFO))
logger.Println(v)
}
func Warn( v ...interface{}){
log.SetPrefix(string(WARNING))
logger.Println(v)
}
func Error( v ...interface{}){
log.SetPrefix(string(ERROR))
logger.Println(v)
}
func Fatal( v ...interface{}){
log.SetPrefix(string(FATAL))
logger.Println(v)
}
func setPrefix(level Level) {
_, file, line, ok := runtime.Caller(DefaultCallerDepth)
if ok {
logPrefix = fmt.Sprintf("[%s][%s:%d]", levelFlags[level], filepath.Base(file), line)
} else {
logPrefix = fmt.Sprintf("[%s]", levelFlags[level])
}
logger.SetPrefix(logPrefix)
}
推荐阅读
- 网络--办公网线布局,网络层协议与应用,广播和广播域概述,ARP协议,ICMP,ping
- AI时代来袭,你的存储做好准备了吗()
- Java基本数据类型及其类型转换
- 最新的前端大厂面经(详解答案)
- 用python实现自动发邮件的功能
- ansible+jenkins发布优化
- 博睿数据亮相 2021 服贸会,以智能运维赋能数字化体验
- 第二十三周作业
- 第二十四周作业