Skip to content

Commit

Permalink
[Elastic Agent] Log the container command output with LOGS_PATH (#25150
Browse files Browse the repository at this point in the history
…) (#25155)

* Log the container command.

* Add changelog.

(cherry picked from commit 8c1b8f2)

Co-authored-by: Blake Rouse <[email protected]>
  • Loading branch information
mergify[bot] and blakerouse authored Apr 20, 2021
1 parent d00615c commit 2419c17
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
1 change: 1 addition & 0 deletions x-pack/elastic-agent/CHANGELOG.next.asciidoc
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,4 @@
- Add status subcommand {pull}24856[24856]
- Add leader_election provider for k8s {pull}24267[24267]
- Add --fleet-server-service-token and FLEET_SERVER_SERVICE_TOKEN options {pull}25083[25083]
- Log output of container to $LOGS_PATH/elastic-agent-start.log when LOGS_PATH set {pull}25150[25150]
25 changes: 22 additions & 3 deletions x-pack/elastic-agent/pkg/agent/cmd/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ all the above actions will be skipped, because the Elastic Agent has already bee
occurs on every start of the container set FLEET_FORCE to 1.
`,
Run: func(c *cobra.Command, args []string) {
if err := containerCmd(streams, c); err != nil {
if err := logContainerCmd(streams, c); err != nil {
logError(streams, err)
os.Exit(1)
}
Expand All @@ -138,6 +138,25 @@ func logInfo(streams *cli.IOStreams, msg string) {
fmt.Fprintln(streams.Out, msg)
}

func logContainerCmd(streams *cli.IOStreams, cmd *cobra.Command) error {
logsPath := envWithDefault("", "LOGS_PATH")
if logsPath != "" {
// log this entire command to a file as well as to the passed streams
if err := os.MkdirAll(logsPath, 0755); err != nil {
return fmt.Errorf("preparing LOGS_PATH(%s) failed: %s", logsPath, err)
}
logPath := filepath.Join(logsPath, "elastic-agent-startup.log")
w, err := os.Create(logPath)
if err != nil {
return fmt.Errorf("opening startup log(%s) failed: %s", logPath, err)
}
defer w.Close()
streams.Out = io.MultiWriter(streams.Out, w)
streams.Err = io.MultiWriter(streams.Out, w)
}
return containerCmd(streams, cmd)
}

func containerCmd(streams *cli.IOStreams, cmd *cobra.Command) error {
// set paths early so all action below use the defined paths
if err := setPaths(); err != nil {
Expand Down Expand Up @@ -274,8 +293,8 @@ func runContainerCmd(streams *cli.IOStreams, cmd *cobra.Command, cfg setupConfig
return err
}
enroll := exec.Command(executable, cmdArgs...)
enroll.Stdout = os.Stdout
enroll.Stderr = os.Stderr
enroll.Stdout = streams.Out
enroll.Stderr = streams.Err
err = enroll.Start()
if err != nil {
return errors.New("failed to execute enrollment command", err)
Expand Down

0 comments on commit 2419c17

Please sign in to comment.