Skip to content

Commit 361dc9e

Browse files
blakerousemergify-bot
authored andcommitted
[Elastic Agent] Log the container command output with LOGS_PATH (#25150)
* Log the container command. * Add changelog. (cherry picked from commit 8c1b8f2)
1 parent b3d01ef commit 361dc9e

2 files changed

Lines changed: 23 additions & 3 deletions

File tree

x-pack/elastic-agent/CHANGELOG.next.asciidoc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,3 +89,4 @@
8989
- Add status subcommand {pull}24856[24856]
9090
- Add leader_election provider for k8s {pull}24267[24267]
9191
- Add --fleet-server-service-token and FLEET_SERVER_SERVICE_TOKEN options {pull}25083[25083]
92+
- Log output of container to $LOGS_PATH/elastic-agent-start.log when LOGS_PATH set {pull}25150[25150]

x-pack/elastic-agent/pkg/agent/cmd/container.go

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ all the above actions will be skipped, because the Elastic Agent has already bee
121121
occurs on every start of the container set FLEET_FORCE to 1.
122122
`,
123123
Run: func(c *cobra.Command, args []string) {
124-
if err := containerCmd(streams, c); err != nil {
124+
if err := logContainerCmd(streams, c); err != nil {
125125
logError(streams, err)
126126
os.Exit(1)
127127
}
@@ -138,6 +138,25 @@ func logInfo(streams *cli.IOStreams, msg string) {
138138
fmt.Fprintln(streams.Out, msg)
139139
}
140140

141+
func logContainerCmd(streams *cli.IOStreams, cmd *cobra.Command) error {
142+
logsPath := envWithDefault("", "LOGS_PATH")
143+
if logsPath != "" {
144+
// log this entire command to a file as well as to the passed streams
145+
if err := os.MkdirAll(logsPath, 0755); err != nil {
146+
return fmt.Errorf("preparing LOGS_PATH(%s) failed: %s", logsPath, err)
147+
}
148+
logPath := filepath.Join(logsPath, "elastic-agent-startup.log")
149+
w, err := os.Create(logPath)
150+
if err != nil {
151+
return fmt.Errorf("opening startup log(%s) failed: %s", logPath, err)
152+
}
153+
defer w.Close()
154+
streams.Out = io.MultiWriter(streams.Out, w)
155+
streams.Err = io.MultiWriter(streams.Out, w)
156+
}
157+
return containerCmd(streams, cmd)
158+
}
159+
141160
func containerCmd(streams *cli.IOStreams, cmd *cobra.Command) error {
142161
// set paths early so all action below use the defined paths
143162
if err := setPaths(); err != nil {
@@ -274,8 +293,8 @@ func runContainerCmd(streams *cli.IOStreams, cmd *cobra.Command, cfg setupConfig
274293
return err
275294
}
276295
enroll := exec.Command(executable, cmdArgs...)
277-
enroll.Stdout = os.Stdout
278-
enroll.Stderr = os.Stderr
296+
enroll.Stdout = streams.Out
297+
enroll.Stderr = streams.Err
279298
err = enroll.Start()
280299
if err != nil {
281300
return errors.New("failed to execute enrollment command", err)

0 commit comments

Comments
 (0)