Skip to content
This repository was archived by the owner on Aug 30, 2024. It is now read-only.

feat: make log file path optional and configurable #423

Merged
merged 3 commits into from
Sep 2, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 23 additions & 14 deletions internal/cmd/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"net/url"
"os"
"os/signal"
"path/filepath"
"syscall"

// We use slog here since agent runs in the background and we can benefit
Expand Down Expand Up @@ -35,34 +34,43 @@ func startCmd() *cobra.Command {
var (
token string
coderURL string
logFile string
)
cmd := &cobra.Command{
Use: "start --coder-url=[coder_url] --token=[token]",
Use: "start --coder-url=<coder_url> --token=<token> --log-file=<path>",
Short: "starts the coder agent",
Long: "starts the coder agent",
Example: `# start the agent and use CODER_URL and CODER_AGENT_TOKEN env vars

coder agent start

# start the agent and connect with a specified url and agent token

coder agent start --coder-url https://my-coder.com --token xxxx-xxxx

# start the agent and write a copy of the log to /tmp/coder-agent.log
# if the file already exists, it will be truncated
coder agent start --log-file=/tmp/coder-agent.log
`,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
sinks := []slog.Sink{
sloghuman.Sink(os.Stderr),
}

file, err := os.OpenFile(filepath.Join(os.TempDir(), "coder-agent.log"), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err == nil && file != nil {
sinks = append(sinks, sloghuman.Sink(file))
}
log := slog.Make(sloghuman.Sink(os.Stderr)).Leveled(slog.LevelDebug)

log := slog.Make(sinks...).Leveled(slog.LevelDebug)
if err != nil {
log.Info(ctx, "failed to open agent log file", slog.Error(err))
// Optional log file path to write
if logFile != "" {
// Truncate the file if it already exists
file, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
// If an error occurs, log it as an error, but consider it non-fatal
log.Warn(ctx, "failed to open log file", slog.Error(err))
} else {
// Log to both standard output and our file
log = slog.Make(
sloghuman.Sink(os.Stderr),
sloghuman.Sink(file),
).Leveled(slog.LevelDebug)
}
}

if coderURL == "" {
var ok bool
coderURL, ok = os.LookupEnv("CODER_URL")
Expand Down Expand Up @@ -113,6 +121,7 @@ coder agent start --coder-url https://my-coder.com --token xxxx-xxxx

cmd.Flags().StringVar(&token, "token", "", "coder agent token")
cmd.Flags().StringVar(&coderURL, "coder-url", "", "coder access url")
cmd.Flags().StringVar(&logFile, "log-file", "", "write a copy of logs to file")

return cmd
}