123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- package fslog
- import (
- "go.uber.org/zap"
- "go.uber.org/zap/zapcore"
- "os"
- "path/filepath"
- "runtime/debug"
- "strings"
- )
- var logger *zap.Logger
- const logDir = "logs"
- func init() {
- if !pathExists(logDir) {
- err := os.MkdirAll(logDir, os.ModeDir|os.ModePerm)
- if err != nil {
- panic(err)
- }
- }
- logFilePath := filepath.Join(logDir, "log")
- file, err := os.Create(logFilePath)
- if err != nil {
- panic(err)
- }
- developmentEncoderConfig := zap.NewDevelopmentEncoderConfig()
- encoder := zapcore.NewConsoleEncoder(developmentEncoderConfig)
- core := zapcore.NewTee(
- zapcore.NewCore(encoder, zapcore.AddSync(file), zapcore.DebugLevel),
- zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), zapcore.DebugLevel),
- )
- logger = zap.New(core, zap.AddCaller())
- }
- func Info(serviceName string, funcName string, callName string, message string) {
- callerFields := getCallerInfoForLog(serviceName, funcName, callName)
- logger.Info(message, callerFields...)
- }
- func Error(serviceName string, funcName string, callName string, message string) {
- callerFields := getCallerInfoForLog(serviceName, funcName, callName)
- logger.Error(message+"\n"+string(debug.Stack()), callerFields...)
- }
- func Debug(serviceName string, funcName string, callName string, message string) {
- callerFields := getCallerInfoForLog(serviceName, funcName, callName)
- logger.Debug(message, callerFields...)
- }
- func Warning(serviceName string, funcName string, callName string, message string) {
- callerFields := getCallerInfoForLog(serviceName, funcName, callName)
- logger.Warn(message, callerFields...)
- }
- func getCallerInfoForLog(serviceName string, funcName string, callName string) []zap.Field {
- fields := make([]zap.Field, 0)
- if strings.Trim(serviceName, " ") != "" {
- fields = append(fields, zap.String("service", serviceName))
- }
- if strings.Trim(funcName, " ") != "" {
- fields = append(fields, zap.String("function", funcName))
- }
- if strings.Trim(callName, " ") != "" {
- fields = append(fields, zap.String("call", callName))
- }
- return fields
- }
- func pathExists(path string) bool {
- _, err := os.Stat(path)
- if err == nil {
- return true
- }
- if os.IsNotExist(err) {
- return false
- }
- return false
- }
|