diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c62cf7f --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +ctdao +logs/* +.idea +go.sum \ No newline at end of file diff --git a/ctdao b/ctdao index 032d61a..fb2ba07 100755 Binary files a/ctdao and b/ctdao differ diff --git a/go.mod b/go.mod index 9bc137b..bb547a9 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,9 @@ module github.com/yifanshaoye/ctdao go 1.18 + +require ( + go.uber.org/atomic v1.9.0 // indirect + go.uber.org/multierr v1.8.0 // indirect + go.uber.org/zap v1.21.0 // indirect +) diff --git a/main.go b/main.go index 973f969..465667a 100644 --- a/main.go +++ b/main.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "github.com/yifanshaoye/ctdao/zaplog" "github.com/yifanshaoye/ctdao/database" ) @@ -9,4 +10,9 @@ import ( func main() { fmt.Println("Hello, World !!!") database.Done() + + //zaplog.SetLogFilePath("./database/access.log") + zaplog.InitZaplog() + zaplog.Info("test", "test log %+v", "zaplog") + zaplog.Error("second", "send log: %+v", "hahah") } diff --git a/zaplog/zaplog.go b/zaplog/zaplog.go new file mode 100644 index 0000000..b178ce6 --- /dev/null +++ b/zaplog/zaplog.go @@ -0,0 +1,77 @@ +package zaplog + +import ( + "errors" + "fmt" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" + "os" + "path/filepath" + "time" +) + +type coreLogger struct { + logPath string + zaplog *zap.Logger + +} + +var logger *coreLogger + +func init() { + path, _ := filepath.Abs("./logs/logger.log") + logger = &coreLogger{logPath: path} +} + +func (lg *coreLogger) initLogger() { + enconf := zap.NewProductionEncoderConfig() + enconf.EncodeTime = func(tm time.Time, enc zapcore.PrimitiveArrayEncoder) { + enc.AppendString(tm.Format("2006-01-02 15:04:05.000")) + } + encoder := zapcore.NewJSONEncoder(enconf) + + fdir := filepath.Dir(lg.logPath) + os.MkdirAll(fdir, 0766) + file, err := os.OpenFile(lg.logPath, os.O_WRONLY|os.O_CREATE, 0666) + if err != nil { + lg.logPath, _= filepath.Abs("./logs/logger.log") + fdir := filepath.Dir(lg.logPath) + os.MkdirAll(fdir, 0766) + file, _ = os.OpenFile(lg.logPath, os.O_WRONLY|os.O_CREATE, 0666) + } + wrteSyncer := zapcore.AddSync(file) + + core := zapcore.NewCore(encoder, wrteSyncer, zapcore.InfoLevel) + + + lg.zaplog = zap.New(core, zap.AddCallerSkip(1), zap.AddCaller()) +} + +// 初始化zaplog, 在写日志之前必须初始化 +func InitZaplog() *coreLogger { + if logger.zaplog == nil { + logger.initLogger() + } + return logger +} + +func SetLogFilePath(path string) error { + apath, err := filepath.Abs(path) + if err != nil { + return errors.New("invalie path !!!") + } + logger.logPath = apath + return nil +} + +func Info(tag, format string, args ...interface{}) { + msg := fmt.Sprintf(format, args...) + logger.zaplog.Info(msg, + zap.String("tag", tag),) +} + +func Error(tag, format string, args ...interface{}) { + msg := fmt.Sprintf(format, args...) + logger.zaplog.Error(msg, + zap.String("tag", tag),) +} \ No newline at end of file