0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Kubebuilderで作成したcontrollerのログに色をつける

Posted at

環境

  • kubebuilder: v4.8.0
  • controller-runtime v0.21.0

コントローラーの雛形を作成

$ kubebuilder init --domain my.domain --repo my.domain/guestbook
$ kubebuilder create api --group webapp --version v1 --kind Guestbook
$ make manifests

これで実行した時のログはこんな感じ

$ make run
...
2025-08-31T14:12:53+09:00	INFO	setup	starting manager
2025-08-31T14:12:53+09:00	INFO	starting server	{"name": "health probe", "addr": "[::]:8081"}
...

ログレベルに色をつける

main.go
	opts := zap.Options{
		Development: true,
	}
	opts.BindFlags(flag.CommandLine)
	flag.Parse()
+	if opts.Development {
+		opts.EncoderConfigOptions = []zap.EncoderConfigOption{func(c *zapcore.EncoderConfig) {
+			c.EncodeLevel = zapcore.CapitalColorLevelEncoder
+		}}
+	}

	ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))

これで実行するとログレベルに色がついて見やすくなる

image.png

デバッグログの出力方法

setupLog.V(1).Info("starting manager")

本番環境で動かす場合

--zap-devel=falseをつけて実行すれば、構造化されて、デバッグログは出力されず、色もつかなくなる

$ go run cmd/main.go --zap-devel=false
{"level":"info","ts":"2025-08-31T14:26:50+09:00","logger":"setup","msg":"starting manager"}
{"level":"info","ts":"2025-08-31T14:26:50+09:00","msg":"starting server","name":"health probe","addr":"[::]:8081"}
...

フラグについてはこちらを参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?