fslog_instance.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package fslog
  2. import (
  3. "go.uber.org/zap"
  4. "go.uber.org/zap/zapcore"
  5. "os"
  6. "path/filepath"
  7. "runtime/debug"
  8. "strings"
  9. )
  10. var logger *zap.Logger
  11. const logDir = "logs"
  12. func init() {
  13. if !pathExists(logDir) {
  14. err := os.MkdirAll(logDir, os.ModeDir|os.ModePerm)
  15. if err != nil {
  16. panic(err)
  17. }
  18. }
  19. logFilePath := filepath.Join(logDir, "log")
  20. file, err := os.Create(logFilePath)
  21. if err != nil {
  22. panic(err)
  23. }
  24. developmentEncoderConfig := zap.NewDevelopmentEncoderConfig()
  25. encoder := zapcore.NewConsoleEncoder(developmentEncoderConfig)
  26. core := zapcore.NewTee(
  27. zapcore.NewCore(encoder, zapcore.AddSync(file), zapcore.DebugLevel),
  28. zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), zapcore.DebugLevel),
  29. )
  30. logger = zap.New(core, zap.AddCaller())
  31. }
  32. func Info(serviceName string, funcName string, callName string, message string) {
  33. callerFields := getCallerInfoForLog(serviceName, funcName, callName)
  34. logger.Info(message, callerFields...)
  35. }
  36. func Error(serviceName string, funcName string, callName string, message string) {
  37. callerFields := getCallerInfoForLog(serviceName, funcName, callName)
  38. logger.Error(message+"\n"+string(debug.Stack()), callerFields...)
  39. }
  40. func Debug(serviceName string, funcName string, callName string, message string) {
  41. callerFields := getCallerInfoForLog(serviceName, funcName, callName)
  42. logger.Debug(message, callerFields...)
  43. }
  44. func Warning(serviceName string, funcName string, callName string, message string) {
  45. callerFields := getCallerInfoForLog(serviceName, funcName, callName)
  46. logger.Warn(message, callerFields...)
  47. }
  48. func getCallerInfoForLog(serviceName string, funcName string, callName string) []zap.Field {
  49. fields := make([]zap.Field, 0)
  50. if strings.Trim(serviceName, " ") != "" {
  51. fields = append(fields, zap.String("service", serviceName))
  52. }
  53. if strings.Trim(funcName, " ") != "" {
  54. fields = append(fields, zap.String("function", funcName))
  55. }
  56. if strings.Trim(callName, " ") != "" {
  57. fields = append(fields, zap.String("call", callName))
  58. }
  59. return fields
  60. }
  61. func pathExists(path string) bool {
  62. _, err := os.Stat(path)
  63. if err == nil {
  64. return true
  65. }
  66. if os.IsNotExist(err) {
  67. return false
  68. }
  69. return false
  70. }