logs.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. package cmd
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "os"
  8. "path/filepath"
  9. "slices"
  10. "time"
  11. "github.com/charmbracelet/crush/internal/config"
  12. "github.com/charmbracelet/log/v2"
  13. "github.com/nxadm/tail"
  14. "github.com/spf13/cobra"
  15. )
  16. const defaultTailLines = 1000
  17. var logsCmd = &cobra.Command{
  18. Use: "logs",
  19. Short: "View crush logs",
  20. Long: `View the logs generated by Crush. This command allows you to see the log output for debugging and monitoring.`,
  21. RunE: func(cmd *cobra.Command, args []string) error {
  22. cwd, err := cmd.Flags().GetString("cwd")
  23. if err != nil {
  24. return fmt.Errorf("failed to get current working directory: %v", err)
  25. }
  26. dataDir, err := cmd.Flags().GetString("data-dir")
  27. if err != nil {
  28. return fmt.Errorf("failed to get data directory: %v", err)
  29. }
  30. follow, err := cmd.Flags().GetBool("follow")
  31. if err != nil {
  32. return fmt.Errorf("failed to get follow flag: %v", err)
  33. }
  34. tailLines, err := cmd.Flags().GetInt("tail")
  35. if err != nil {
  36. return fmt.Errorf("failed to get tail flag: %v", err)
  37. }
  38. log.SetLevel(log.DebugLevel)
  39. log.SetOutput(os.Stdout)
  40. cfg, err := config.Load(cwd, dataDir, false)
  41. if err != nil {
  42. return fmt.Errorf("failed to load configuration: %v", err)
  43. }
  44. logsFile := filepath.Join(cfg.Options.DataDirectory, "logs", "crush.log")
  45. _, err = os.Stat(logsFile)
  46. if os.IsNotExist(err) {
  47. log.Warn("Looks like you are not in a crush project. No logs found.")
  48. return nil
  49. }
  50. if follow {
  51. return followLogs(cmd.Context(), logsFile, tailLines)
  52. }
  53. return showLogs(logsFile, tailLines)
  54. },
  55. }
  56. func init() {
  57. logsCmd.Flags().BoolP("follow", "f", false, "Follow log output")
  58. logsCmd.Flags().IntP("tail", "t", defaultTailLines, "Show only the last N lines default: 1000 for performance")
  59. }
  60. func followLogs(ctx context.Context, logsFile string, tailLines int) error {
  61. t, err := tail.TailFile(logsFile, tail.Config{
  62. Follow: false,
  63. ReOpen: false,
  64. Logger: tail.DiscardingLogger,
  65. })
  66. if err != nil {
  67. return fmt.Errorf("failed to tail log file: %v", err)
  68. }
  69. var lines []string
  70. for line := range t.Lines {
  71. if line.Err != nil {
  72. continue
  73. }
  74. lines = append(lines, line.Text)
  75. if len(lines) > tailLines {
  76. lines = lines[len(lines)-tailLines:]
  77. }
  78. }
  79. t.Stop()
  80. for _, line := range lines {
  81. printLogLine(line)
  82. }
  83. if len(lines) == tailLines {
  84. fmt.Fprintf(os.Stderr, "\nShowing last %d lines. Full logs available at: %s\n", tailLines, logsFile)
  85. fmt.Fprintf(os.Stderr, "Following new log entries...\n\n")
  86. }
  87. t, err = tail.TailFile(logsFile, tail.Config{
  88. Follow: true,
  89. ReOpen: true,
  90. Logger: tail.DiscardingLogger,
  91. Location: &tail.SeekInfo{Offset: 0, Whence: io.SeekEnd},
  92. })
  93. if err != nil {
  94. return fmt.Errorf("failed to tail log file: %v", err)
  95. }
  96. defer t.Stop()
  97. for {
  98. select {
  99. case line := <-t.Lines:
  100. if line.Err != nil {
  101. continue
  102. }
  103. printLogLine(line.Text)
  104. case <-ctx.Done():
  105. return nil
  106. }
  107. }
  108. }
  109. func showLogs(logsFile string, tailLines int) error {
  110. t, err := tail.TailFile(logsFile, tail.Config{
  111. Follow: false,
  112. ReOpen: false,
  113. Logger: tail.DiscardingLogger,
  114. MaxLineSize: 0,
  115. })
  116. if err != nil {
  117. return fmt.Errorf("failed to tail log file: %v", err)
  118. }
  119. defer t.Stop()
  120. var lines []string
  121. for line := range t.Lines {
  122. if line.Err != nil {
  123. continue
  124. }
  125. lines = append(lines, line.Text)
  126. if len(lines) > tailLines {
  127. lines = lines[len(lines)-tailLines:]
  128. }
  129. }
  130. for _, line := range lines {
  131. printLogLine(line)
  132. }
  133. if len(lines) == tailLines {
  134. fmt.Fprintf(os.Stderr, "\nShowing last %d lines. Full logs available at: %s\n", tailLines, logsFile)
  135. }
  136. return nil
  137. }
  138. func printLogLine(lineText string) {
  139. var data map[string]any
  140. if err := json.Unmarshal([]byte(lineText), &data); err != nil {
  141. return
  142. }
  143. msg := data["msg"]
  144. level := data["level"]
  145. otherData := []any{}
  146. keys := []string{}
  147. for k := range data {
  148. keys = append(keys, k)
  149. }
  150. slices.Sort(keys)
  151. for _, k := range keys {
  152. switch k {
  153. case "msg", "level", "time":
  154. continue
  155. case "source":
  156. source, ok := data[k].(map[string]any)
  157. if !ok {
  158. continue
  159. }
  160. sourceFile := fmt.Sprintf("%s:%d", source["file"], int(source["line"].(float64)))
  161. otherData = append(otherData, "source", sourceFile)
  162. default:
  163. otherData = append(otherData, k, data[k])
  164. }
  165. }
  166. log.SetTimeFunction(func(_ time.Time) time.Time {
  167. // parse the timestamp from the log line if available
  168. t, err := time.Parse(time.RFC3339, data["time"].(string))
  169. if err != nil {
  170. return time.Now() // fallback to current time if parsing fails
  171. }
  172. return t
  173. })
  174. switch level {
  175. case "INFO":
  176. log.Info(msg, otherData...)
  177. case "DEBUG":
  178. log.Debug(msg, otherData...)
  179. case "ERROR":
  180. log.Error(msg, otherData...)
  181. case "WARN":
  182. log.Warn(msg, otherData...)
  183. default:
  184. log.Info(msg, otherData...)
  185. }
  186. }