Skip to content

Commit 83e4d48

Browse files
authored
Add option for logging in JSON format (#152)
Add option for logging in JSON format
1 parent 3cb9309 commit 83e4d48

File tree

13 files changed

+107
-53
lines changed

13 files changed

+107
-53
lines changed

THIRD_PARTY_LICENSES

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,3 +414,29 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
414414
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
415415
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
416416
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
417+
418+
------
419+
420+
** github.com/rs/zerolog; version v1.18.0 --
421+
422+
MIT License
423+
424+
Copyright (c) 2017 Olivier Poitrey
425+
426+
Permission is hereby granted, free of charge, to any person obtaining a copy
427+
of this software and associated documentation files (the "Software"), to deal
428+
in the Software without restriction, including without limitation the rights
429+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
430+
copies of the Software, and to permit persons to whom the Software is
431+
furnished to do so, subject to the following conditions:
432+
433+
The above copyright notice and this permission notice shall be included in all
434+
copies or substantial portions of the Software.
435+
436+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
437+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
438+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
439+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
440+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
441+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
442+
SOFTWARE.

cmd/node-termination-handler.go

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ package main
1515

1616
import (
1717
"fmt"
18-
"log"
1918
"os"
2019
"os/signal"
2120
"syscall"
@@ -27,6 +26,8 @@ import (
2726
"github.com/aws/aws-node-termination-handler/pkg/interruptioneventstore"
2827
"github.com/aws/aws-node-termination-handler/pkg/node"
2928
"github.com/aws/aws-node-termination-handler/pkg/webhook"
29+
"github.com/rs/zerolog"
30+
"github.com/rs/zerolog/log"
3031
)
3132

3233
const (
@@ -37,22 +38,29 @@ const (
3738
type monitorFunc func(chan<- interruptionevent.InterruptionEvent, chan<- interruptionevent.InterruptionEvent, *ec2metadata.Service) error
3839

3940
func main() {
41+
// Zerolog uses json formatting by default, so change that to a human-readable format instead
42+
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339, NoColor: true})
43+
4044
signalChan := make(chan os.Signal, 1)
4145
signal.Notify(signalChan, syscall.SIGTERM)
4246
defer signal.Stop(signalChan)
4347

4448
nthConfig, err := config.ParseCliArgs()
4549
if err != nil {
46-
log.Fatalln("Failed to parse cli args: ", err)
50+
log.Fatal().Err(err).Msg("Failed to parse cli args,")
4751
}
4852

4953
err = webhook.ValidateWebhookConfig(nthConfig)
5054
if err != nil {
51-
log.Fatalln("Webhook validation failed: ", err)
55+
log.Fatal().Err(err).Msg("Webhook validation failed,")
5256
}
5357
node, err := node.New(nthConfig)
5458
if err != nil {
55-
log.Fatalln("Unable to instantiate a node for various kubernetes node functions: ", err)
59+
log.Fatal().Err(err).Msg("Unable to instantiate a node for various kubernetes node functions,")
60+
}
61+
62+
if nthConfig.JsonLogging {
63+
log.Logger = zerolog.New(os.Stderr).With().Timestamp().Logger()
5664
}
5765

5866
imds := ec2metadata.New(nthConfig.MetadataURL, nthConfig.MetadataTries)
@@ -63,7 +71,7 @@ func main() {
6371
if nthConfig.EnableScheduledEventDraining {
6472
err = handleRebootUncordon(interruptionEventStore, *node)
6573
if err != nil {
66-
log.Printf("Unable to complete the uncordon after reboot workflow on startup: %v\n", err)
74+
log.Printf("Unable to complete the uncordon after reboot workflow on startup: %v", err)
6775
}
6876
}
6977

@@ -93,11 +101,11 @@ func main() {
93101
}
94102

95103
go watchForInterruptionEvents(interruptionChan, interruptionEventStore, nodeMetadata)
96-
log.Println("Started watching for interruption events")
97-
log.Println("Kubernetes AWS Node Termination Handler has started successfully!")
104+
log.Print("Started watching for interruption events")
105+
log.Print("Kubernetes AWS Node Termination Handler has started successfully!")
98106

99107
go watchForCancellationEvents(cancelChan, interruptionEventStore, node, nodeMetadata)
100-
log.Println("Started watching for event cancellations")
108+
log.Print("Started watching for event cancellations")
101109

102110
for range time.NewTicker(1 * time.Second).C {
103111
select {
@@ -108,7 +116,7 @@ func main() {
108116
drainOrCordonIfNecessary(interruptionEventStore, *node, nthConfig, nodeMetadata)
109117
}
110118
}
111-
log.Println("AWS Node Termination Handler is shutting down")
119+
log.Print("AWS Node Termination Handler is shutting down")
112120
}
113121

114122
func handleRebootUncordon(interruptionEventStore *interruptioneventstore.Store, node node.Node) error {
@@ -134,25 +142,25 @@ func handleRebootUncordon(interruptionEventStore *interruptioneventstore.Store,
134142
func watchForInterruptionEvents(interruptionChan <-chan interruptionevent.InterruptionEvent, interruptionEventStore *interruptioneventstore.Store, nodeMetadata ec2metadata.NodeMetadata) {
135143
for {
136144
interruptionEvent := <-interruptionChan
137-
log.Printf("Got interruption event from channel %+v %+v\n", nodeMetadata, interruptionEvent)
145+
log.Printf("Got interruption event from channel %+v %+v", nodeMetadata, interruptionEvent)
138146
interruptionEventStore.AddInterruptionEvent(&interruptionEvent)
139147
}
140148
}
141149

142150
func watchForCancellationEvents(cancelChan <-chan interruptionevent.InterruptionEvent, interruptionEventStore *interruptioneventstore.Store, node *node.Node, nodeMetadata ec2metadata.NodeMetadata) {
143151
for {
144152
interruptionEvent := <-cancelChan
145-
log.Printf("Got cancel event from channel %+v %+v\n", nodeMetadata, interruptionEvent)
153+
log.Printf("Got cancel event from channel %+v %+v", nodeMetadata, interruptionEvent)
146154
interruptionEventStore.CancelInterruptionEvent(interruptionEvent.EventID)
147155
if interruptionEventStore.ShouldUncordonNode() {
148-
log.Println("Uncordoning the node due to a cancellation event")
156+
log.Print("Uncordoning the node due to a cancellation event")
149157
err := node.Uncordon()
150158
if err != nil {
151159
log.Printf("Uncordoning the node failed: %v", err)
152160
}
153161
node.RemoveNTHLabels()
154162
} else {
155-
log.Println("Another interruption event is active, not uncordoning the node")
163+
log.Print("Another interruption event is active, not uncordoning the node")
156164
}
157165
}
158166
}
@@ -162,23 +170,23 @@ func drainOrCordonIfNecessary(interruptionEventStore *interruptioneventstore.Sto
162170
if drainEvent.PreDrainTask != nil {
163171
err := drainEvent.PreDrainTask(*drainEvent, node)
164172
if err != nil {
165-
log.Println("There was a problem executing the pre-drain task: ", err)
173+
log.Printf("There was a problem executing the pre-drain task: %v", err)
166174
}
167175
}
168176
if nthConfig.CordonOnly {
169177
err := node.Cordon()
170178
if err != nil {
171-
log.Println("There was a problem while trying to cordon the node: ", err)
179+
log.Printf("There was a problem while trying to cordon the node: %v", err)
172180
os.Exit(1)
173181
}
174-
log.Printf("Node %q successfully cordoned.\n", nthConfig.NodeName)
182+
log.Printf("Node %q successfully cordoned.", nthConfig.NodeName)
175183
} else {
176184
err := node.CordonAndDrain()
177185
if err != nil {
178-
log.Println("There was a problem while trying to cordon and drain the node: ", err)
186+
log.Printf("There was a problem while trying to cordon and drain the node: %v", err)
179187
os.Exit(1)
180188
}
181-
log.Printf("Node %q successfully cordoned and drained.\n", nthConfig.NodeName)
189+
log.Printf("Node %q successfully cordoned and drained.", nthConfig.NodeName)
182190
}
183191
interruptionEventStore.MarkAllAsDrained()
184192
if nthConfig.WebhookURL != "" {

config/helm/aws-node-termination-handler/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ Parameter | Description | Default
6767
`enableSpotInterruptionDraining` | If true, drain nodes when the spot interruption termination notice is received | `true`
6868
`metadataTries` | The number of times to try requesting metadata. If you would like 2 retries, set metadata-tries to 3. | `3`
6969
`cordonOnly` | If true, nodes will be cordoned but not drained when an interruption event occurs. | `false`
70+
`jsonLogging` | If true, use JSON-formatted logs instead of human readable logs. | `false`
7071
`affinity` | node/pod affinities | None
7172
`podAnnotations` | annotations to add to each pod | `{}`
7273
`priorityClassName` | Name of the priorityClass | `system-node-critical`

config/helm/aws-node-termination-handler/templates/daemonset.yaml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,8 @@ spec:
109109
value: {{ .Values.metadataTries | quote }}
110110
- name: CORDON_ONLY
111111
value: {{ .Values.cordonOnly | quote }}
112+
- name: JSON_LOGGING
113+
value: {{ .Values.jsonLogging | quote }}
112114
resources:
113115
{{- toYaml .Values.resources | nindent 12 }}
114116
{{- with .Values.nodeSelector }}

go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ module github.com/aws/aws-node-termination-handler
33
go 1.14
44

55
require (
6+
github.com/rs/zerolog v1.18.0
67
golang.org/x/time v0.0.0-20190921001708-c4c64cad1fd0 // indirect
78
k8s.io/api v0.0.0-20191010143144-fbf594f18f80
89
k8s.io/apimachinery v0.0.0-20191016060620-86f2f1b9c076

go.sum

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk
3030
github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
3131
github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk=
3232
github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
33+
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
3334
github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE=
3435
github.com/davecgh/go-spew v0.0.0-20151105211317-5215b55f46b2/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
3536
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -153,6 +154,7 @@ github.com/opencontainers/go-digest v1.0.0-rc1/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQ
153154
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
154155
github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU=
155156
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
157+
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
156158
github.com/pmezard/go-difflib v0.0.0-20151028094244-d8ed2627bdf0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
157159
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
158160
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
@@ -164,6 +166,9 @@ github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y8
164166
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
165167
github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
166168
github.com/remyoudompheng/bigfft v0.0.0-20170806203942-52369c62f446/go.mod h1:uYEyJGbgTkfkS4+E/PavXkNJcbFIpEtjt2B0KDQ5+9M=
169+
github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ=
170+
github.com/rs/zerolog v1.18.0 h1:CbAm3kP2Tptby1i9sYy2MGRg0uxIN9cyDb59Ys7W8z8=
171+
github.com/rs/zerolog v1.18.0/go.mod h1:9nvC1axdVrAHcu/s9taAVfBuIdTZLVQmKQyvrUjF5+I=
167172
github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
168173
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
169174
github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4=
@@ -187,6 +192,7 @@ github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0
187192
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
188193
github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0=
189194
github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
195+
github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q=
190196
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
191197
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
192198
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
@@ -214,6 +220,7 @@ golang.org/x/net v0.0.0-20190311183353-d8887717615a h1:oWX7TPOiFAMXLq8o0ikBYfCJV
214220
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
215221
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
216222
golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
223+
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
217224
golang.org/x/net v0.0.0-20190812203447-cdfb69ac37fc h1:gkKoSkUmnU6bpS/VhkuO27bzQeSA51uaEfbOW5dNb68=
218225
golang.org/x/net v0.0.0-20190812203447-cdfb69ac37fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
219226
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
@@ -257,6 +264,8 @@ golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3
257264
golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
258265
golang.org/x/tools v0.0.0-20190614205625-5aca471b1d59/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
259266
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
267+
golang.org/x/tools v0.0.0-20190828213141-aed303cbaa74/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
268+
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
260269
gonum.org/v1/gonum v0.0.0-20190331200053-3d26580ed485/go.mod h1:2ltnJ7xHfj0zHS40VVPYEAAMTa3ZGguvHGBSJeRWqE0=
261270
gonum.org/v1/netlib v0.0.0-20190313105609-8cb42192e0e0/go.mod h1:wa6Ws7BG/ESfp6dHfk7C6KdzKA7wR7u/rKwOGE66zvw=
262271
gonum.org/v1/netlib v0.0.0-20190331212654-76723241ea4e/go.mod h1:kS+toOQn6AQKjmKJ7gzohV1XkqsFehRA2FbsbkopSuQ=
@@ -309,7 +318,6 @@ k8s.io/kube-openapi v0.0.0-20190816220812-743ec37842bf h1:EYm5AW/UUDbnmnI+gK0TJD
309318
k8s.io/kube-openapi v0.0.0-20190816220812-743ec37842bf/go.mod h1:1TqjTSzOxsLGIKfj0lK8EeCP7K1iUG65v09OM0/WG5E=
310319
k8s.io/kubectl v0.0.0-20191016234702-5d0b8f240400 h1:IeGIAmvzKqd9LLSWCXXFKbenbJCu9faeIulMgYz77YY=
311320
k8s.io/kubectl v0.0.0-20191016234702-5d0b8f240400/go.mod h1:939lYu2PWLrk5t7xWN3amNIvJlJCa7KQfPZ2+cLrnJA=
312-
k8s.io/kubernetes v1.17.2 h1:g1UFZqFQsYx88xMUks4PKC6tsNcekxe0v06fcVGRwVE=
313321
k8s.io/metrics v0.0.0-20191014074242-8b0351268f72/go.mod h1:ie2c8bq97BFtf7noiNVVJmLhEjShRhE4KBVFxeZCSjs=
314322
k8s.io/utils v0.0.0-20191010214722-8d271d903fe4 h1:Gi+/O1saihwDqnlmC8Vhv1M5Sp4+rbOmK9TbsLn8ZEA=
315323
k8s.io/utils v0.0.0-20191010214722-8d271d903fe4/go.mod h1:sZAwmy6armz5eXlNoLmJcl4F1QuKu7sr+mFQ0byX7Ew=

pkg/config/config.go

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,10 @@ package config
1616
import (
1717
"flag"
1818
"fmt"
19-
"log"
2019
"os"
2120
"strconv"
21+
22+
"github.com/rs/zerolog/log"
2223
)
2324

2425
const (
@@ -49,6 +50,8 @@ const (
4950
metadataTriesConfigKey = "METADATA_TRIES"
5051
metadataTriesDefault = 3
5152
cordonOnly = "CORDON_ONLY"
53+
jsonLoggingConfigKey = "JSON_LOGGING"
54+
jsonLoggingDefault = false
5255
)
5356

5457
//Config arguments set via CLI, environment variables, or defaults
@@ -69,6 +72,7 @@ type Config struct {
6972
EnableSpotInterruptionDraining bool
7073
MetadataTries int
7174
CordonOnly bool
75+
JsonLogging bool
7276
}
7377

7478
//ParseCliArgs parses cli arguments and uses environment variables as fallback values
@@ -99,13 +103,14 @@ func ParseCliArgs() (config Config, err error) {
99103
flag.BoolVar(&config.EnableSpotInterruptionDraining, "enable-spot-interruption-draining", getBoolEnv(enableSpotInterruptionDrainingConfigKey, enableSpotInterruptionDrainingDefault), "If true, drain nodes when the spot interruption termination notice is received")
100104
flag.IntVar(&config.MetadataTries, "metadata-tries", getIntEnv(metadataTriesConfigKey, metadataTriesDefault), "The number of times to try requesting metadata. If you would like 2 retries, set metadata-tries to 3.")
101105
flag.BoolVar(&config.CordonOnly, "cordon-only", getBoolEnv(cordonOnly, false), "If true, nodes will be cordoned but not drained when an interruption event occurs.")
106+
flag.BoolVar(&config.JsonLogging, "json-logging", getBoolEnv(jsonLoggingConfigKey, jsonLoggingDefault), "If true, use JSON-formatted logs instead of human readable logs.")
102107

103108
flag.Parse()
104109

105110
if isConfigProvided("pod-termination-grace-period", podTerminationGracePeriodConfigKey) && isConfigProvided("grace-period", gracePeriodConfigKey) {
106-
log.Println("Deprecated argument \"grace-period\" and the replacement argument \"pod-termination-grace-period\" was provided. Using the newer argument \"pod-termination-grace-period\"")
111+
log.Print("Deprecated argument \"grace-period\" and the replacement argument \"pod-termination-grace-period\" was provided. Using the newer argument \"pod-termination-grace-period\"")
107112
} else if isConfigProvided("grace-period", gracePeriodConfigKey) {
108-
log.Println("Deprecated argument \"grace-period\" was provided. This argument will eventually be removed. Please switch to \"pod-termination-grace-period\" instead.")
113+
log.Print("Deprecated argument \"grace-period\" was provided. This argument will eventually be removed. Please switch to \"pod-termination-grace-period\" instead.")
109114
config.PodTerminationGracePeriod = gracePeriod
110115
}
111116

@@ -132,7 +137,8 @@ func ParseCliArgs() (config Config, err error) {
132137
"\tenable-scheduled-event-draining: %t,\n"+
133138
"\tenable-spot-interruption-draining: %t,\n"+
134139
"\tmetadata-tries: %d,\n"+
135-
"\tcordon-only: %t,\n",
140+
"\tcordon-only: %t,\n"+
141+
"\tjson-logging: %t,\n",
136142

137143
config.DryRun,
138144
config.NodeName,
@@ -147,6 +153,7 @@ func ParseCliArgs() (config Config, err error) {
147153
config.EnableSpotInterruptionDraining,
148154
config.MetadataTries,
149155
config.CordonOnly,
156+
config.JsonLogging,
150157
)
151158

152159
return config, err

pkg/ec2metadata/ec2metadata.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,13 @@ import (
1717
"encoding/json"
1818
"fmt"
1919
"io/ioutil"
20-
"log"
2120
"math/rand"
2221
"net/http"
2322
"strconv"
2423
"sync"
2524
"time"
25+
26+
"github.com/rs/zerolog/log"
2627
)
2728

2829
const (
@@ -218,7 +219,7 @@ func (e *Service) getV2Token() (string, int, error) {
218219
httpReq := func() (*http.Response, error) {
219220
return e.httpClient.Do(req)
220221
}
221-
log.Println("Trying to get token from IMDSv2")
222+
log.Print("Trying to get token from IMDSv2")
222223
resp, err := retry(1, 2*time.Second, httpReq)
223224
if err != nil {
224225
return "", -1, err
@@ -235,7 +236,7 @@ func (e *Service) getV2Token() (string, int, error) {
235236
if err != nil {
236237
return "", -1, fmt.Errorf("IMDS v2 Token TTL header not sent in response: %w", err)
237238
}
238-
log.Println("Got token from IMDSv2")
239+
log.Print("Got token from IMDSv2")
239240
return string(token), ttl, nil
240241
}
241242

@@ -258,8 +259,8 @@ func retry(attempts int, sleep time.Duration, httpReq func() (*http.Response, er
258259
jitter := time.Duration(rand.Int63n(int64(sleep)))
259260
sleep = sleep + jitter/2
260261

261-
log.Printf("Request failed. Attempts remaining: %d\n", attempts)
262-
log.Printf("Sleep for %s seconds\n", sleep)
262+
log.Printf("Request failed. Attempts remaining: %d", attempts)
263+
log.Printf("Sleep for %s seconds", sleep)
263264
time.Sleep(sleep)
264265
return retry(attempts, 2*sleep, httpReq)
265266
}

0 commit comments

Comments
 (0)