logging.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. package logging
  2. import (
  3. "bytes"
  4. "context"
  5. "database/sql"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "log/slog"
  10. "os"
  11. "runtime/debug"
  12. "strings"
  13. "time"
  14. "github.com/go-logfmt/logfmt"
  15. "github.com/google/uuid"
  16. "github.com/sst/opencode/internal/db"
  17. "github.com/sst/opencode/internal/pubsub"
  18. )
  19. type Log struct {
  20. ID string
  21. SessionID string
  22. Timestamp time.Time
  23. Level string
  24. Message string
  25. Attributes map[string]string
  26. CreatedAt time.Time
  27. }
  28. const (
  29. EventLogCreated pubsub.EventType = "log_created"
  30. )
  31. type Service interface {
  32. pubsub.Subscriber[Log]
  33. Create(ctx context.Context, timestamp time.Time, level, message string, attributes map[string]string, sessionID string) error
  34. ListBySession(ctx context.Context, sessionID string) ([]Log, error)
  35. ListAll(ctx context.Context, limit int) ([]Log, error)
  36. }
  37. type service struct {
  38. db *db.Queries
  39. broker *pubsub.Broker[Log]
  40. }
  41. var globalLoggingService *service
  42. func InitService(dbConn *sql.DB) error {
  43. if globalLoggingService != nil {
  44. return fmt.Errorf("logging service already initialized")
  45. }
  46. queries := db.New(dbConn)
  47. broker := pubsub.NewBroker[Log]()
  48. globalLoggingService = &service{
  49. db: queries,
  50. broker: broker,
  51. }
  52. return nil
  53. }
  54. func GetService() Service {
  55. if globalLoggingService == nil {
  56. panic("logging service not initialized. Call logging.InitService() first.")
  57. }
  58. return globalLoggingService
  59. }
  60. func (s *service) Create(ctx context.Context, timestamp time.Time, level, message string, attributes map[string]string, sessionID string) error {
  61. if level == "" {
  62. level = "info"
  63. }
  64. var attributesJSON sql.NullString
  65. if len(attributes) > 0 {
  66. attributesBytes, err := json.Marshal(attributes)
  67. if err != nil {
  68. return fmt.Errorf("failed to marshal log attributes: %w", err)
  69. }
  70. attributesJSON = sql.NullString{String: string(attributesBytes), Valid: true}
  71. }
  72. dbLog, err := s.db.CreateLog(ctx, db.CreateLogParams{
  73. ID: uuid.New().String(),
  74. SessionID: sql.NullString{String: sessionID, Valid: sessionID != ""},
  75. Timestamp: timestamp.UTC().Format(time.RFC3339Nano),
  76. Level: level,
  77. Message: message,
  78. Attributes: attributesJSON,
  79. })
  80. if err != nil {
  81. return fmt.Errorf("db.CreateLog: %w", err)
  82. }
  83. log := s.fromDBItem(dbLog)
  84. s.broker.Publish(EventLogCreated, log)
  85. return nil
  86. }
  87. func (s *service) ListBySession(ctx context.Context, sessionID string) ([]Log, error) {
  88. dbLogs, err := s.db.ListLogsBySession(ctx, sql.NullString{String: sessionID, Valid: true})
  89. if err != nil {
  90. return nil, fmt.Errorf("db.ListLogsBySession: %w", err)
  91. }
  92. logs := make([]Log, len(dbLogs))
  93. for i, dbSess := range dbLogs {
  94. logs[i] = s.fromDBItem(dbSess)
  95. }
  96. return logs, nil
  97. }
  98. func (s *service) ListAll(ctx context.Context, limit int) ([]Log, error) {
  99. dbLogs, err := s.db.ListAllLogs(ctx, int64(limit))
  100. if err != nil {
  101. return nil, fmt.Errorf("db.ListAllLogs: %w", err)
  102. }
  103. logs := make([]Log, len(dbLogs))
  104. for i, dbSess := range dbLogs {
  105. logs[i] = s.fromDBItem(dbSess)
  106. }
  107. return logs, nil
  108. }
  109. func (s *service) Subscribe(ctx context.Context) <-chan pubsub.Event[Log] {
  110. return s.broker.Subscribe(ctx)
  111. }
  112. func (s *service) fromDBItem(item db.Log) Log {
  113. log := Log{
  114. ID: item.ID,
  115. SessionID: item.SessionID.String,
  116. Level: item.Level,
  117. Message: item.Message,
  118. }
  119. // Parse timestamp from ISO string
  120. timestamp, err := time.Parse(time.RFC3339Nano, item.Timestamp)
  121. if err == nil {
  122. log.Timestamp = timestamp
  123. } else {
  124. log.Timestamp = time.Now() // Fallback
  125. }
  126. // Parse created_at from ISO string
  127. createdAt, err := time.Parse(time.RFC3339Nano, item.CreatedAt)
  128. if err == nil {
  129. log.CreatedAt = createdAt
  130. } else {
  131. log.CreatedAt = time.Now() // Fallback
  132. }
  133. if item.Attributes.Valid && item.Attributes.String != "" {
  134. if err := json.Unmarshal([]byte(item.Attributes.String), &log.Attributes); err != nil {
  135. slog.Error("Failed to unmarshal log attributes", "log_id", item.ID, "error", err)
  136. log.Attributes = make(map[string]string)
  137. }
  138. } else {
  139. log.Attributes = make(map[string]string)
  140. }
  141. return log
  142. }
  143. func Create(ctx context.Context, timestamp time.Time, level, message string, attributes map[string]string, sessionID string) error {
  144. return GetService().Create(ctx, timestamp, level, message, attributes, sessionID)
  145. }
  146. func ListBySession(ctx context.Context, sessionID string) ([]Log, error) {
  147. return GetService().ListBySession(ctx, sessionID)
  148. }
  149. func ListAll(ctx context.Context, limit int) ([]Log, error) {
  150. return GetService().ListAll(ctx, limit)
  151. }
  152. func Subscribe(ctx context.Context) <-chan pubsub.Event[Log] {
  153. return GetService().Subscribe(ctx)
  154. }
  155. type slogWriter struct{}
  156. func (sw *slogWriter) Write(p []byte) (n int, err error) {
  157. // Example: time=2024-05-09T12:34:56.789-05:00 level=INFO msg="User request" session=xyz foo=bar
  158. d := logfmt.NewDecoder(bytes.NewReader(p))
  159. for d.ScanRecord() {
  160. var timestamp time.Time
  161. var level string
  162. var message string
  163. var sessionID string
  164. var attributes map[string]string
  165. attributes = make(map[string]string)
  166. hasTimestamp := false
  167. for d.ScanKeyval() {
  168. key := string(d.Key())
  169. value := string(d.Value())
  170. switch key {
  171. case "time":
  172. parsedTime, timeErr := time.Parse(time.RFC3339Nano, value)
  173. if timeErr != nil {
  174. parsedTime, timeErr = time.Parse(time.RFC3339, value)
  175. if timeErr != nil {
  176. slog.Error("Failed to parse time in slog writer", "value", value, "error", timeErr)
  177. timestamp = time.Now().UTC()
  178. hasTimestamp = true
  179. continue
  180. }
  181. }
  182. timestamp = parsedTime
  183. hasTimestamp = true
  184. case "level":
  185. level = strings.ToLower(value)
  186. case "msg", "message":
  187. message = value
  188. case "session_id":
  189. sessionID = value
  190. default:
  191. attributes[key] = value
  192. }
  193. }
  194. if d.Err() != nil {
  195. return len(p), fmt.Errorf("logfmt.ScanRecord: %w", d.Err())
  196. }
  197. if !hasTimestamp {
  198. timestamp = time.Now()
  199. }
  200. // Create log entry via the service (non-blocking or handle error appropriately)
  201. // Using context.Background() as this is a low-level logging write.
  202. go func(timestamp time.Time, level, message string, attributes map[string]string, sessionID string) { // Run in a goroutine to avoid blocking slog
  203. if globalLoggingService == nil {
  204. // If the logging service is not initialized, log the message to stderr
  205. // fmt.Fprintf(os.Stderr, "ERROR [logging.slogWriter]: logging service not initialized\n")
  206. return
  207. }
  208. if err := Create(context.Background(), timestamp, level, message, attributes, sessionID); err != nil {
  209. // Log internal error using a more primitive logger to avoid loops
  210. fmt.Fprintf(os.Stderr, "ERROR [logging.slogWriter]: failed to persist log: %v\n", err)
  211. }
  212. }(timestamp, level, message, attributes, sessionID)
  213. }
  214. if d.Err() != nil {
  215. return len(p), fmt.Errorf("logfmt.ScanRecord final: %w", d.Err())
  216. }
  217. return len(p), nil
  218. }
  219. func NewSlogWriter() io.Writer {
  220. return &slogWriter{}
  221. }
  222. // RecoverPanic is a common function to handle panics gracefully.
  223. // It logs the error, creates a panic log file with stack trace,
  224. // and executes an optional cleanup function.
  225. func RecoverPanic(name string, cleanup func()) {
  226. if r := recover(); r != nil {
  227. errorMsg := fmt.Sprintf("Panic in %s: %v", name, r)
  228. // Use slog directly here, as our service might be the one panicking.
  229. slog.Error(errorMsg)
  230. // status.Error(errorMsg)
  231. timestamp := time.Now().Format("20060102-150405")
  232. filename := fmt.Sprintf("opencode-panic-%s-%s.log", name, timestamp)
  233. file, err := os.Create(filename)
  234. if err != nil {
  235. errMsg := fmt.Sprintf("Failed to create panic log file '%s': %v", filename, err)
  236. slog.Error(errMsg)
  237. // status.Error(errMsg)
  238. } else {
  239. defer file.Close()
  240. fmt.Fprintf(file, "Panic in %s: %v\n\n", name, r)
  241. fmt.Fprintf(file, "Time: %s\n\n", time.Now().Format(time.RFC3339))
  242. fmt.Fprintf(file, "Stack Trace:\n%s\n", string(debug.Stack())) // Capture stack trace
  243. infoMsg := fmt.Sprintf("Panic details written to %s", filename)
  244. slog.Info(infoMsg)
  245. // status.Info(infoMsg)
  246. }
  247. if cleanup != nil {
  248. cleanup()
  249. }
  250. }
  251. }