Files
yetone ceeb73a0f1 app: the desktop app writes its log to app.log; magpie log and Settings › About › Log find it
rayem1w on X (0.1.2330, macOS) was asked for ~/Library/Logs/magpie/serve.log
while chasing a Codex "hit a snag" through the gateway, and had no such
folder. Only the launch agent (magpie daemon install, written by launchd)
and a gateway magpie tui left running wrote a log; the app opened from the
Finder, the Dock or the Start menu logged to a stderr nobody reads, on
every system.

Now runGUI and runPanel (magpie, app, tray, panel, a window view, a
magpie: link) call applog.Start before gui.Run. It sends the standard
logger (the gateway, the plugin host, providers and Wails' error handler
all log through it) to app.log as well as stderr, and points
debug.SetCrashOutput at it so a panic's trace is there too:

  macOS    ~/Library/Logs/magpie/app.log
  Windows  %LOCALAPPDATA%\magpie\logs\app.log
  Linux    $XDG_STATE_HOME/magpie/app.log, else ~/.local/state/magpie/app.log
  portable data/logs/app.log

app.log, not serve.log: on a Mac launchd writes serve.log for the service,
another process. The file is 0600. At 5 MiB it becomes app.old.log (two
files at most); when another magpie (an update's new process) rotated it
already, it is only opened again; when it can't be moved it is emptied.
stderr goes first, through a writer that never fails, since io.MultiWriter
stops at a failed writer and an app opened from Explorer has no stderr.

Secrets: the log calls name header names and paths without queries; no
key or token was found logged (grep of log.Print* in gateway, provider,
plugin, gui, agent). scrub masks bearer/basic credentials, key/token query
parameters and sk-, AIza, gh?_ and JWT shapes anyway.

How a user finds it: Settings › About › Log, with the path, Copy and an
Open that shows its folder (POST /api/settings/log/reveal; the row is
hidden in magpie web, which writes no file). magpie log prints where every
log is (the app's, app.old.log, the service's, the tui's background
serve.log); --path the app's alone, -n N its last lines, -f follows it
across a rotation. Docs: reference.md, gui-shell.md, site start (FAQ "Where
is magpie's log?" and the CLI table) and privacy (files on your computer),
en/zh/ja.

Run:
At 227ce6074 on origin/main fbb1b36d1:
- mote: go test ./internal/applog ./internal/appdir ./internal/cli ok;
  -run TestCoreScriptBudget ./internal/gui ok; GOOS=windows go vet
  ./internal/... and GOOS=linux go vet -tags nogui ./internal/... ok;
  gofmt -l clean. GUI, chromium: about-log (5 languages x 1100/420, and
  no row without a log), about-website, i18n-keys: 24 of 25, the one red
  "a plugin's words are its own" ("Unmarked") is the same at origin/main
  fbb1b36d1 (#4524).
- WSL (magpie-desktop), webkit: about-log and about-website 21 of 21.
- Windows (win-run): applog, appdir, tui ok; cli ok but
  TestLibraryMCPHub's TempDir cleanup (#4140, mcp-npm, not this change).
- WSL full go test -tags nogui -timeout 45m ./... at the previous base
  03f609e3f: every package ok but reds that fail the same at origin/main
  03f609e3f alone: TestSettingsSaveKeepsWhatItDoesNotSend (#4514),
  TestNoCommandBypassesProc (#4491), internal/agent's install-detection
  tests (#4033, #3548), and TestCoreScriptBudget, which was this change
  (app.js 321 over): its comment is cut to one line and both budgets
  are raised by the remaining 124 bytes, with no room added.
- Broken by hand: with startLog left out of runGUI, TestTheAppWritesItsLog
  is red ("app wrote no log: open .../Library/Logs/magpie/app.log: no such
  file or directory"); with proc.UserPath taken out of openApp,
  TestGatewayStartsGetUserPath is red ("runGUI doesn't call
  proc.UserPath"). The guard now follows a start into a function or func
  var of this package, since the Wails start sits behind openApp for the
  test.
- Real use on mote: the GUI build, magpie app in a sandbox HOME, wrote
  ~/Library/Logs/magpie/app.log (0600) with its "started" line; magpie
  log and magpie log -n 3 printed it.
Not tried: the app opened from Windows Explorer or a Linux desktop
launcher for real (the paths are unit-tested per OS, the writer on
Windows and Linux); the full GUI suite (running on WSL after the push,
reds filed if they fail at origin/main too).
2026-10-31 14:45:22 +08:00

188 lines
5.0 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package cli
// magpie log: where magpie's logs are, and the app's last lines. The app
// opened from the Finder, the Dock or the Start menu writes its log to a
// file (applog), which a user asked for it finds here or in Settings ›
// About › Log (rayem1w on X had been told of serve.log, which only the
// service writes).
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/yetone/magpie/internal/applog"
"github.com/yetone/magpie/internal/daemon"
"github.com/yetone/magpie/internal/tui"
)
const logUsage = `usage: magpie log [--path] [-n N] [-f]
where magpie's logs are on this computer: the app's own (the app, the menu bar and the
panel write it, wherever they were opened from), the one before it, and the logs of
magpie serve as a service (magpie daemon) or left running by magpie tui, when there are.
--path the app's log alone, its path only
-n N the app log's last N lines (100 with -f)
-f the app log's last lines, then each line as it is written, until Ctrl+C
Send the app's log with a report. It holds what magpie did, not your keys, prompts or replies.`
// logCmd: magpie log [--path] [-n N] [-f]
func logCmd(args []string) error {
pathOnly, follow, lines := false, false, -1
for i := 0; i < len(args); i++ {
switch a := args[i]; {
case a == "--path":
pathOnly = true
case a == "-f" || a == "--follow":
follow = true
case a == "-n" || a == "--lines":
if i+1 == len(args) {
return errors.New("-n takes a number of lines (magpie log -n 200)")
}
i++
n, err := strconv.Atoi(args[i])
if err != nil || n < 0 {
return fmt.Errorf("-n takes a number of lines, not %q (magpie log -n 200)", args[i])
}
lines = n
default:
return fmt.Errorf("unknown argument %s (magpie log [--path] [-n N] [-f])", a)
}
}
path := applog.Path()
switch {
case pathOnly && (follow || lines >= 0):
return errors.New("--path prints the path alone: use it without -n or -f")
case pathOnly:
fmt.Println(path)
return nil
case follow || lines >= 0:
if lines < 0 {
lines = 100
}
return tailLog(os.Stdout, path, lines, follow, nil)
}
fmt.Print(logsHere(path))
return nil
}
// logsHere says where each of magpie's logs is: the app's, always, and
// the others that are there.
func logsHere(path string) string {
var b strings.Builder
fmt.Fprintf(&b, "%s\n", path)
if _, err := os.Stat(path); err != nil {
fmt.Fprintf(&b, " the app's log: nothing yet; the app writes it once it is opened\n")
} else {
fmt.Fprintf(&b, " the app's log (Settings › About › Log); magpie log -f follows it\n")
}
if old := filepath.Join(filepath.Dir(path), applog.OldName); exists(old) {
fmt.Fprintf(&b, "%s\n the app's log before it, kept once it reached %d MiB\n", old, applog.Limit>>20)
}
if st, err := daemon.Get(); err == nil && st.Installed && st.Logs != "" {
fmt.Fprintf(&b, "%s\n magpie serve as a service (magpie daemon)\n", st.Logs)
}
if bg := tui.BackgroundLog(); exists(bg) {
fmt.Fprintf(&b, "%s\n magpie serve left running by magpie tui as it quit\n", bg)
}
return b.String()
}
func exists(p string) bool {
_, err := os.Stat(p)
return err == nil
}
// tailLog writes the last n lines of the log at path to w, then, with
// follow, what is written to it after, until stop is closed (nil: until
// magpie is ended). A log rotated meanwhile is read again from its start.
func tailLog(w io.Writer, path string, n int, follow bool, stop <-chan struct{}) error {
f, err := os.Open(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) && follow {
fmt.Fprintf(os.Stderr, "magpie: %s isn't there yet: waiting for the app to write it\n", path)
} else if errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("%s isn't there yet: the app writes it once it is opened", path)
} else {
return err
}
}
var at int64
if f != nil {
b, err := io.ReadAll(f)
if err != nil {
f.Close()
return err
}
at = int64(len(b))
w.Write(lastLines(b, n))
}
if !follow {
if f != nil {
f.Close()
}
return nil
}
tick := time.NewTicker(300 * time.Millisecond)
defer tick.Stop()
defer func() {
if f != nil {
f.Close()
}
}()
for {
select {
case <-stop:
return nil
case <-tick.C:
}
// a new file at path (rotated, or written for the first time):
// read it from its start
if fi, err := os.Stat(path); err == nil {
var mine os.FileInfo
if f != nil {
mine, _ = f.Stat()
}
if f == nil || mine == nil || !os.SameFile(fi, mine) || fi.Size() < at {
if nf, err := os.Open(path); err == nil {
if f != nil {
// what the old file got after the last read first
io.Copy(w, f)
f.Close()
}
f, at = nf, 0
}
}
}
if f == nil {
continue
}
n, _ := io.Copy(w, bufio.NewReader(f))
at += n
}
}
// lastLines is b's last n lines.
func lastLines(b []byte, n int) []byte {
if n == 0 {
return nil
}
i := len(b)
if i > 0 && b[i-1] == '\n' {
i--
}
for ; n > 0; n-- {
i = bytes.LastIndexByte(b[:i], '\n')
if i < 0 {
return b
}
}
return b[i+1:]
}