Skip to content

Commit 7f925c7

Browse files
committed
Handle log streams correctly for default stderr, file-only, and file+stderr logging.
1 parent 9c9cdce commit 7f925c7

File tree

4 files changed

+338
-2
lines changed

4 files changed

+338
-2
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/*
2+
Copyright 2025 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package flags
18+
19+
import (
20+
"fmt"
21+
"io"
22+
"os"
23+
"path/filepath"
24+
25+
"github.com/spf13/pflag"
26+
logsapi "k8s.io/component-base/logs/api/v1"
27+
)
28+
29+
// getFlagString is a small helper to read a string flag from the given FlagSet.
30+
func getFlagString(fs *pflag.FlagSet, name string) string {
31+
if f := fs.Lookup(name); f != nil {
32+
return f.Value.String()
33+
}
34+
return ""
35+
}
36+
37+
// getFlagBool is a small helper to read a bool flag from the given FlagSet.
38+
func getFlagBool(fs *pflag.FlagSet, name string) bool {
39+
if f := fs.Lookup(name); f != nil {
40+
val, _ := fs.GetBool(name)
41+
return val
42+
}
43+
return false
44+
}
45+
46+
// ComputeLoggingOptions computes logsapi.LoggingOptions based on klog-related flags present in fs.
47+
//
48+
// Semantics:
49+
// - By default (no log-file OR logtostderr=true), logs go to os.Stderr.
50+
// - If --log-file is set AND --logtostderr=false, logs go to the file.
51+
// - If --alsologtostderr=true, logs also go to os.Stderr
52+
func ComputeLoggingOptions(fs *pflag.FlagSet) (*logsapi.LoggingOptions, error) {
53+
logFilePath := getFlagString(fs, "log-file")
54+
logToStderr := getFlagBool(fs, "logtostderr")
55+
alsoLogToStderr := getFlagBool(fs, "alsologtostderr")
56+
57+
// default: both to stderr
58+
var infoW, errW io.Writer = os.Stderr, os.Stderr
59+
60+
if logFilePath != "" && !logToStderr {
61+
dir := filepath.Dir(logFilePath)
62+
if err := os.MkdirAll(dir, 0o755); err != nil {
63+
return nil, fmt.Errorf("failed to create log directory %q: %w", dir, err)
64+
}
65+
f, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
66+
if err != nil {
67+
return nil, fmt.Errorf("failed to open log file %q: %w", logFilePath, err)
68+
}
69+
70+
// Primary output is now the file
71+
infoW = f
72+
errW = f
73+
74+
if alsoLogToStderr {
75+
infoW = io.MultiWriter(f, os.Stderr)
76+
errW = io.MultiWriter(f, os.Stderr)
77+
}
78+
}
79+
80+
return &logsapi.LoggingOptions{
81+
ErrorStream: errW,
82+
InfoStream: infoW,
83+
}, nil
84+
}
Lines changed: 246 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,246 @@
1+
/*
2+
Copyright 2025 The Kubernetes Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package flags
18+
19+
import (
20+
"io"
21+
"os"
22+
"path/filepath"
23+
"reflect"
24+
"strings"
25+
"testing"
26+
27+
"github.com/spf13/pflag"
28+
)
29+
30+
// --------------------- HELPERS ---------------------
31+
32+
func newTestFlagSet(t *testing.T, logFile string, logToStderr, alsoLogToStderr bool) *pflag.FlagSet {
33+
t.Helper()
34+
fs := pflag.NewFlagSet("test", pflag.ContinueOnError)
35+
fs.String("log-file", "", "")
36+
fs.Bool("logtostderr", true, "")
37+
fs.Bool("alsologtostderr", false, "")
38+
39+
if logFile != "" {
40+
if err := fs.Set("log-file", logFile); err != nil {
41+
t.Fatalf("set log-file: %v", err)
42+
}
43+
}
44+
if err := fs.Set("logtostderr", boolToString(logToStderr)); err != nil {
45+
t.Fatalf("set logtostderr: %v", err)
46+
}
47+
if err := fs.Set("alsologtostderr", boolToString(alsoLogToStderr)); err != nil {
48+
t.Fatalf("set alsologtostderr: %v", err)
49+
}
50+
return fs
51+
}
52+
53+
func boolToString(b bool) string {
54+
if b {
55+
return "true"
56+
}
57+
return "false"
58+
}
59+
60+
// assertStreams checks the actual streams against expected values
61+
func assertStreams(t *testing.T, actualInfo, actualErr any, expectedInfo, expectedErr any) {
62+
t.Helper()
63+
64+
check := func(name string, actual, expected any) {
65+
if expected == nil {
66+
if actual != nil {
67+
t.Fatalf("%s: expected nil, got %T", name, actual)
68+
}
69+
return
70+
}
71+
72+
if reflect.TypeOf(actual) != reflect.TypeOf(expected) {
73+
t.Fatalf("%s type mismatch: expected %T, got %T", name, expected, actual)
74+
}
75+
76+
if f, ok := expected.(*os.File); ok {
77+
if actual.(*os.File) != f {
78+
t.Fatalf("%s pointer mismatch: expected same *os.File", name)
79+
}
80+
}
81+
if expected == os.Stderr {
82+
if actual != os.Stderr {
83+
t.Fatalf("%s mismatch: expected os.Stderr", name)
84+
}
85+
}
86+
87+
// For io.MultiWriter, type check is sufficient
88+
}
89+
90+
check("InfoStream", actualInfo, expectedInfo)
91+
check("ErrorStream", actualErr, expectedErr)
92+
}
93+
94+
// --------------------- TESTS ---------------------
95+
96+
func TestComputeLoggingOptions_DefaultToStderr(t *testing.T) {
97+
fs := newTestFlagSet(t, "", true, false)
98+
opts, err := ComputeLoggingOptions(fs)
99+
if err != nil {
100+
t.Fatalf("ComputeLoggingOptions error: %v", err)
101+
}
102+
assertStreams(t, opts.InfoStream, opts.ErrorStream, os.Stderr, os.Stderr)
103+
}
104+
105+
func TestComputeLoggingOptions_LogFileIgnoredWhenLogToStderrTrue(t *testing.T) {
106+
tmp := t.TempDir()
107+
logPath := filepath.Join(tmp, "subdir", "ca.log")
108+
109+
fs := newTestFlagSet(t, logPath, true, false)
110+
opts, err := ComputeLoggingOptions(fs)
111+
if err != nil {
112+
t.Fatalf("ComputeLoggingOptions error: %v", err)
113+
}
114+
115+
if _, statErr := os.Stat(logPath); !os.IsNotExist(statErr) {
116+
t.Fatalf("expected no log file created at %q, statErr=%v", logPath, statErr)
117+
}
118+
119+
assertStreams(t, opts.InfoStream, opts.ErrorStream, os.Stderr, os.Stderr)
120+
}
121+
122+
func TestComputeLoggingOptions_LogFileOnly(t *testing.T) {
123+
tmp := t.TempDir()
124+
logPath := filepath.Join(tmp, "nested", "onlyfile.log")
125+
126+
fs := newTestFlagSet(t, logPath, false, false)
127+
opts, err := ComputeLoggingOptions(fs)
128+
if err != nil {
129+
t.Fatalf("ComputeLoggingOptions error: %v", err)
130+
}
131+
132+
if _, statErr := os.Stat(logPath); statErr != nil {
133+
t.Fatalf("expected log file created at %q, err=%v", logPath, statErr)
134+
}
135+
136+
// Streams should be the same file writer
137+
file := opts.InfoStream.(*os.File)
138+
assertStreams(t, opts.InfoStream, opts.ErrorStream, file, file)
139+
140+
// Write and verify content
141+
msg := "hello-file-only\n"
142+
if _, err := file.Write([]byte(msg)); err != nil {
143+
t.Fatalf("write to file failed: %v", err)
144+
}
145+
data, err := os.ReadFile(logPath)
146+
if err != nil {
147+
t.Fatalf("read log file failed: %v", err)
148+
}
149+
if !strings.Contains(string(data), msg) {
150+
t.Fatalf("log file does not contain expected content")
151+
}
152+
}
153+
154+
func TestComputeLoggingOptions_LogFileAlsoToStderr(t *testing.T) {
155+
tmp := t.TempDir()
156+
logPath := filepath.Join(tmp, "withstderr", "combo.log")
157+
158+
fs := newTestFlagSet(t, logPath, false, true)
159+
opts, err := ComputeLoggingOptions(fs)
160+
if err != nil {
161+
t.Fatalf("ComputeLoggingOptions error: %v", err)
162+
}
163+
164+
// File must exist
165+
if _, statErr := os.Stat(logPath); statErr != nil {
166+
t.Fatalf("expected log file created at %q, err=%v", logPath, statErr)
167+
}
168+
169+
file, err := os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, 0o644)
170+
if err != nil {
171+
t.Fatalf("failed to open log file to build expected writer: %v", err)
172+
}
173+
defer file.Close()
174+
175+
expectedWriter := io.MultiWriter(os.Stderr, file)
176+
177+
// Assert streams against expected MultiWriter
178+
assertStreams(t, opts.InfoStream, opts.ErrorStream, expectedWriter, expectedWriter)
179+
180+
// Write and verify content appears in the file
181+
msg := "hello-also-stderr\n"
182+
if _, err := opts.InfoStream.Write([]byte(msg)); err != nil {
183+
t.Fatalf("write to InfoStream failed: %v", err)
184+
}
185+
data, err := os.ReadFile(logPath)
186+
if err != nil {
187+
t.Fatalf("read log file failed: %v", err)
188+
}
189+
if !strings.Contains(string(data), msg) {
190+
t.Fatalf("log file does not contain expected content")
191+
}
192+
}
193+
194+
func TestComputeLoggingOptions_CreateDirError(t *testing.T) {
195+
tmp := t.TempDir()
196+
notADirPath := filepath.Join(tmp, "notadir")
197+
if err := os.WriteFile(notADirPath, []byte("x"), 0o644); err != nil {
198+
t.Fatalf("prepare file failed: %v", err)
199+
}
200+
logPath := filepath.Join(notADirPath, "child", "ca.log")
201+
202+
fs := newTestFlagSet(t, logPath, false, false)
203+
_, err := ComputeLoggingOptions(fs)
204+
if err == nil || !strings.Contains(err.Error(), "failed to create log directory") {
205+
t.Fatalf("expected create dir error, got: %v", err)
206+
}
207+
}
208+
209+
func TestComputeLoggingOptions_OpenFileError(t *testing.T) {
210+
tmp := t.TempDir()
211+
dirAsFile := filepath.Join(tmp, "adir")
212+
if err := os.MkdirAll(dirAsFile, 0o755); err != nil {
213+
t.Fatalf("prepare dir failed: %v", err)
214+
}
215+
216+
fs := newTestFlagSet(t, dirAsFile, false, false)
217+
_, err := ComputeLoggingOptions(fs)
218+
if err == nil || !strings.Contains(err.Error(), "failed to open log file") {
219+
t.Fatalf("expected open file error, got: %v", err)
220+
}
221+
}
222+
223+
func TestComputeLoggingOptions_WriterInterfaceUsable(t *testing.T) {
224+
tmp := t.TempDir()
225+
logPath := filepath.Join(tmp, "writeusable", "ca.log")
226+
227+
fs := newTestFlagSet(t, logPath, false, false)
228+
opts, err := ComputeLoggingOptions(fs)
229+
if err != nil {
230+
t.Fatalf("ComputeLoggingOptions error: %v", err)
231+
}
232+
233+
file := opts.ErrorStream.(*os.File)
234+
n, err := file.Write([]byte("err-stream\n"))
235+
if err != nil || n == 0 {
236+
t.Fatalf("failed writing via ErrorStream: n=%d err=%v", n, err)
237+
}
238+
239+
data, err := os.ReadFile(logPath)
240+
if err != nil {
241+
t.Fatalf("read log file failed: %v", err)
242+
}
243+
if !strings.Contains(string(data), "err-stream") {
244+
t.Fatalf("log file does not contain expected err-stream content")
245+
}
246+
}

cluster-autoscaler/go.sum

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -675,4 +675,4 @@ sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxO
675675
sigs.k8s.io/structured-merge-diff/v6 v6.3.0 h1:jTijUJbW353oVOd9oTlifJqOGEkUw2jB/fXCbTiQEco=
676676
sigs.k8s.io/structured-merge-diff/v6 v6.3.0/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE=
677677
sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs=
678-
sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4=
678+
sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4=

cluster-autoscaler/main.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -370,7 +370,13 @@ func main() {
370370
}
371371

372372
logs.InitLogs()
373-
if err := logsapi.ValidateAndApply(loggingConfig, featureGate); err != nil {
373+
374+
opts, err := flags.ComputeLoggingOptions(pflag.CommandLine)
375+
if err != nil {
376+
klog.Fatalf("Failed to configure logging: %v", err)
377+
}
378+
379+
if err := logsapi.ValidateAndApplyWithOptions(loggingConfig, opts, featureGate); err != nil {
374380
klog.Fatalf("Failed to validate and apply logging configuration: %v", err)
375381
}
376382

0 commit comments

Comments
 (0)