async.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package audit
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "os"
  7. udeModel "udeServer/internal/model"
  8. )
  9. // AsyncInsertLog inserts the log entry in a background goroutine. When the
  10. // insert fails, the entry is appended to log_fallback.jsonl so the audit
  11. // chain never silently loses data.
  12. func AsyncInsertLog(logModel udeModel.TSystemLogModel, entry *udeModel.TSystemLog) {
  13. go func(e *udeModel.TSystemLog) {
  14. defer func() {
  15. if rec := recover(); rec != nil {
  16. fmt.Printf("panic in log insert: %v\n", rec)
  17. }
  18. }()
  19. if _, insErr := logModel.Insert(context.Background(), e); insErr != nil {
  20. fmt.Printf("system log insert failed: %v\n", insErr)
  21. data, mErr := json.Marshal(e)
  22. if mErr != nil {
  23. fmt.Printf("marshal fallback log error: %v\n", mErr)
  24. return
  25. }
  26. // JSON Line格式
  27. f, fErr := os.OpenFile("log_fallback.jsonl", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
  28. if fErr != nil {
  29. fmt.Printf("open fallback file error: %v\n", fErr)
  30. return
  31. }
  32. defer func() {
  33. if cErr := f.Close(); cErr != nil {
  34. fmt.Printf("close fallback file error: %v\n", cErr)
  35. }
  36. }()
  37. if _, wErr := f.WriteString(string(data) + "\n"); wErr != nil {
  38. fmt.Printf("write fallback log error: %v\n", wErr)
  39. }
  40. }
  41. }(entry)
  42. }