Skip to content

Commit

Permalink
[u] 日志模块更新,添加配置文件
Browse files Browse the repository at this point in the history
  • Loading branch information
skycandy committed Aug 30, 2021
1 parent 5a4ac05 commit 4a2cf49
Show file tree
Hide file tree
Showing 7 changed files with 158 additions and 93 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
logs/*
*.log
22 changes: 15 additions & 7 deletions config/configRead.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,23 @@ import (
"fmt"
"io/ioutil"

"github.com/skycandyzhe/go-com/file"
"gopkg.in/yaml.v2"
)

//解析yml文件
type BaseInfo struct {
Version string `yaml:"version"`
DebugFlag bool `yaml:"debugFlag"`
Timelimit int `yaml:"timelimit"`
Console bool `yaml:"console"`
Logs LogsEntity `yaml:"logs"`
}

type LogsEntity struct {
Log_level string `yaml:"log_level"`
Log_path string `yaml:"log_path"`
Err_path string `yaml:"err_path"`
// Log_level string `yaml:"log_level"`
LogName string `yaml:"logname"`
Log_path string `yaml:"log_path"`
Err_path string `yaml:"err_path"`
}

func (c *BaseInfo) GetConf(filepath string) *BaseInfo {
Expand All @@ -38,7 +40,13 @@ func (c *BaseInfo) GetConf(filepath string) *BaseInfo {
var Conf *BaseInfo

func init() {
Conf = &BaseInfo{}
Conf = Conf.GetConf("config.yaml")
fmt.Println("read config.yaml :", Conf)
if file.CheckFileIsExist("log_config.yaml") {
Conf = &BaseInfo{}
Conf = Conf.GetConf("log_config.yaml")
fmt.Println("read config.yaml :", Conf)
} else {
Conf = nil
fmt.Println("not found log_config.yaml")
}

}
17 changes: 15 additions & 2 deletions file/filerw.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package file

import (
"fmt"
"io"
"io/ioutil"
"os"
)

func checkFileIsExist(filename string) bool {
func CheckFileIsExist(filename string) bool {
if _, err := os.Stat(filename); os.IsNotExist(err) {
return false
}
Expand All @@ -15,7 +16,7 @@ func checkFileIsExist(filename string) bool {
func WriteStr(data string, filename string) error {
var f *os.File
var err error
if checkFileIsExist(filename) { //如果文件存在
if CheckFileIsExist(filename) { //如果文件存在
f, _ = os.OpenFile(filename, os.O_APPEND, 0666) //打开文件
} else {
f, _ = os.Create(filename) //创建文件
Expand All @@ -26,6 +27,7 @@ func WriteStr(data string, filename string) error {
return err

}
return nil

}
func WriteByte(data []byte, filename string) {
Expand Down Expand Up @@ -137,3 +139,14 @@ func Exists(path string) bool {
}
return true
}

func Mkdir(path string) bool {
err := os.Mkdir(path, os.ModePerm)
if err != nil {
fmt.Printf("mkdir failed![%v]\n", err)
} else {
fmt.Printf("mkdir %s success!\n", path)
return true
}
return false
}
25 changes: 25 additions & 0 deletions log_config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

version : 1.0
debugFlag: false
console: true
logs:
logname: test
logpath: logs
err_path: logs/err

# DebugLevel Level = iota - 1
# // InfoLevel is the default logging priority.
# InfoLevel
# // WarnLevel logs are more important than Info, but don't need individual
# // human review.
# WarnLevel
# // ErrorLevel logs are high-priority. If an application is running smoothly,
# // it shouldn't generate any error-level logs.
# ErrorLevel
# // DPanicLevel logs are particularly important errors. In development the
# // logger panics after writing the message.
# DPanicLevel
# // PanicLevel logs a message, then panics.
# PanicLevel
# // FatalLevel logs a message, then calls os.Exit(1).
# FatalLevel
16 changes: 16 additions & 0 deletions log_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package test

import (
"fmt"
"testing"

"github.com/skycandyzhe/go-com/config"
"github.com/skycandyzhe/go-com/logger"
)

func TestParseRule(t *testing.T) {
fmt.Println(config.Conf)
logger.Logger.Info("info test")
logger.Logger.Debug("debug test")
logger.Logger.Error("debug test")
}
137 changes: 69 additions & 68 deletions logger/logInit.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,67 @@
package logger

import (
"fmt"
"io"
"os"
"path"
"strings"
"time"

"github.com/skycandyzhe/go-com/config"
"github.com/skycandyzhe/go-com/file"

rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)

var Logger *zap.SugaredLogger
// var Logger *zap.SugaredLogger

// var ErrLvel = zapcore.ErrorLevel
// var InfoLevel = zapcore.InfoLevel
// var EnableConsole = true
// var InfoLogPath=""
// var ErrLogPath=""
var (
Logger *zap.SugaredLogger
ErrLvel = zapcore.ErrorLevel
InfoLevel = zapcore.InfoLevel
EnableConsole = true
InfoLogPath = "logs"
ErrLogPath = "logs/err"
LOG_Name = "msg"
)

func init() {

if config.Conf != nil {
EnableConsole = config.Conf.Console
if config.Conf.DebugFlag {
fmt.Println("need debug log")
InfoLevel = zapcore.DebugLevel
}
InfoLogPath = config.Conf.Logs.Log_path

ErrLogPath = config.Conf.Logs.Err_path
if InfoLogPath == "" {
InfoLogPath = "logs"
}
if ErrLogPath == "" {
ErrLogPath = "logs/err"
}
LOG_Name = config.Conf.Logs.LogName
if LOG_Name == "" {
LOG_Name = "msg"
}

}
if !file.Exists(InfoLogPath) {
file.Mkdir(InfoLogPath)
}
if !file.Exists(ErrLogPath) {
file.Mkdir(ErrLogPath)
}
// 设置一些基本日志格式 具体含义还比较好理解,直接看zap源码也不难懂
encoder := zapcore.NewConsoleEncoder(zapcore.EncoderConfig{
MessageKey: "msg",
Expand All @@ -34,26 +80,37 @@ func init() {

// 实现两个判断日志等级的interface
infoLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl >= zapcore.InfoLevel
return lvl >= InfoLevel
})

errorLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl >= zapcore.ErrorLevel
return lvl >= ErrLvel
})

// 获取 info、error日志文件的io.Writer 抽象 getWriter() 在下方实现

infoWriter := getWriter(config.Conf.Logs.Log_path)
errorWriter := getWriter(config.Conf.Logs.Err_path)
infoWriter := getWriter(path.Join(InfoLogPath, LOG_Name))
errorWriter := getWriter(path.Join(ErrLogPath, LOG_Name))

// 最后创建具体的Logger
core := zapcore.NewTee(
//zapcore.NewCore(zapcore.NewConsoleEncoder(enConfig), zapcore.AddSync(infoWriter), infoLevel),
zapcore.NewCore(encoder, zapcore.AddSync(infoWriter), infoLevel),
zapcore.NewCore(encoder, zapcore.AddSync(errorWriter), errorLevel),
zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), infoLevel),
)

var core zapcore.Core
if EnableConsole {
fmt.Print("need console ")
core = zapcore.NewTee(
//zapcore.NewCore(zapcore.NewConsoleEncoder(enConfig), zapcore.AddSync(infoWriter), infoLevel),
zapcore.NewCore(encoder, zapcore.AddSync(infoWriter), infoLevel),
zapcore.NewCore(encoder, zapcore.AddSync(errorWriter), errorLevel),
zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), infoLevel),
)

} else {
core = zapcore.NewTee(
//zapcore.NewCore(zapcore.NewConsoleEncoder(enConfig), zapcore.AddSync(infoWriter), infoLevel),
zapcore.NewCore(encoder, zapcore.AddSync(infoWriter), infoLevel),
zapcore.NewCore(encoder, zapcore.AddSync(errorWriter), errorLevel),
)
}
log := zap.New(core, zap.AddCaller()) // 需要传入 zap.AddCaller() 才会显示打日志点的文件名和行数, 有点小坑
Logger = log.Sugar()
}
Expand All @@ -63,7 +120,7 @@ func getWriter(filename string) io.Writer {
// demo.log是指向最新日志的链接
// 保存7天内的日志,每1小时(整点)分割一次日志
hook, err := rotatelogs.New(
strings.Replace(filename, ".log", "", -1) + "-%Y%m%d%H.log", // 没有使用go风格反人类的format格式
strings.ReplaceAll(filename, ".log", "") + "-%Y%m%d%H.log", // 没有使用go风格反人类的format格式
//rotatelogs.WithLinkName(filename),
//rotatelogs.WithMaxAge(time.Hour*24*7),
//rotatelogs.WithRotationTime(time.Hour),
Expand All @@ -74,59 +131,3 @@ func getWriter(filename string) io.Writer {
}
return hook
}

// func Debug(args ...interface{}) {
// Logger.Debug(args...)
// }

// func Debugf(template string, args ...interface{}) {
// Logger.Debugf(template, args...)
// }

// func Info(args ...interface{}) {
// Logger.Info(args...)
// }

// func Infof(template string, args ...interface{}) {
// Logger.Infof(template, args...)
// }

// func Warn(args ...interface{}) {
// Logger.Warn(args...)
// }

// func Warnf(template string, args ...interface{}) {
// Logger.Warnf(template, args...)
// }

// func Error(args ...interface{}) {
// Logger.Error(args...)
// }

// func Errorf(template string, args ...interface{}) {
// Logger.Errorf(template, args...)
// }

// func DPanic(args ...interface{}) {
// Logger.DPanic(args...)
// }

// func DPanicf(template string, args ...interface{}) {
// Logger.DPanicf(template, args...)
// }

// func Panic(args ...interface{}) {
// Logger.Panic(args...)
// }

// func Panicf(template string, args ...interface{}) {
// Logger.Panicf(template, args...)
// }

// func Fatal(args ...interface{}) {
// Logger.Fatal(args...)
// }

// func Fatalf(template string, args ...interface{}) {
// Logger.Fatalf(template, args...)
// }
Loading

0 comments on commit 4a2cf49

Please sign in to comment.