Skip to content

Commit 04d7706

Browse files
authored
Merge pull request #11 from flyhope/4-log-write-to-file
log write to file
2 parents de6f293 + 47883ab commit 04d7706

File tree

8 files changed

+173
-24
lines changed

8 files changed

+173
-24
lines changed

comm/config.go

Lines changed: 41 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,31 +5,45 @@ import (
55
"gopkg.in/yaml.v3"
66
"os"
77
"path/filepath"
8-
"strings"
98
"sync"
109
)
1110

12-
// ShowKConfig 获取k.yaml配置
13-
var ShowKConfig = sync.OnceValue(func() *KConfig {
14-
config := &KConfig{
11+
// ShowKubeteaConfig 获取k.yaml配置
12+
var ShowKubeteaConfig = sync.OnceValue(func() *KubeteaConfig {
13+
config := &KubeteaConfig{
1514
ClusterByLabel: "app",
16-
ClusterFilters: []string{"*"},
1715
PodCacheLivetime: 10,
16+
Log: KubeteaConfigLog{
17+
Dir: "~/.kubetea/logs",
18+
FileTotalMax: 10,
19+
Level: logrus.InfoLevel,
20+
},
21+
ClusterFilters: []string{"*"},
1822
}
1923

2024
// 文件件在才继续加载配置
21-
configFilePath := Context.String("config")
22-
if strings.HasPrefix(configFilePath, "~") {
23-
homeDir, err := os.UserHomeDir()
24-
if err != nil {
25-
logrus.Warnln(err)
25+
configFilePath := FixPath(Context.String("config"))
26+
27+
_, errStat := os.Stat(configFilePath)
28+
if os.IsNotExist(errStat) {
29+
configFileDir := filepath.Dir(configFilePath)
30+
if errMkdir := os.MkdirAll(configFileDir, os.ModePerm); errMkdir != nil {
31+
logrus.Warnln(errMkdir)
2632
} else {
27-
configFilePath = filepath.Join(homeDir, configFilePath[1:])
33+
// 文件不存在,写入一份默认配置
34+
yamlData, err := yaml.Marshal(&config)
35+
if err != nil {
36+
logrus.Warnln(err)
37+
} else {
38+
errWrite := os.WriteFile(configFilePath, yamlData, 0664)
39+
if errWrite != nil {
40+
logrus.WithFields(logrus.Fields{"path": configFilePath}).Warnln(errWrite)
41+
}
42+
}
2843
}
29-
}
30-
_, errStat := os.Stat(configFilePath)
31-
if !os.IsNotExist(errStat) {
32-
// 读取YAML文件内容
44+
45+
} else {
46+
// 文件存在,读取YAML文件内容
3347
yamlFile, err := os.ReadFile(configFilePath)
3448
if err != nil {
3549
logrus.WithFields(logrus.Fields{"config": configFilePath}).Fatalf("Failed to read YAML file: %v", err)
@@ -45,8 +59,16 @@ var ShowKConfig = sync.OnceValue(func() *KConfig {
4559
return config
4660
})
4761

48-
type KConfig struct {
49-
ClusterByLabel string `yaml:"cluster_by_label"`
50-
ClusterFilters []string `yaml:"cluster_filters"`
51-
PodCacheLivetime uint32 `yaml:"pod_cache_livetime_second"`
62+
// KubeteaConfig YAML配置定义
63+
type KubeteaConfig struct {
64+
ClusterByLabel string `yaml:"cluster_by_label"`
65+
PodCacheLivetime uint32 `yaml:"pod_cache_livetime_second"`
66+
Log KubeteaConfigLog `yaml:"log"`
67+
ClusterFilters []string `yaml:"cluster_filters"`
68+
}
69+
70+
type KubeteaConfigLog struct {
71+
Dir string `yaml:"dir"`
72+
FileTotalMax int `yaml:"file_total_max"`
73+
Level logrus.Level `yaml:"level"`
5274
}

comm/file.go

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package comm
2+
3+
import (
4+
"fmt"
5+
"github.com/sirupsen/logrus"
6+
"os"
7+
"path/filepath"
8+
"sort"
9+
"strings"
10+
"time"
11+
)
12+
13+
type FileInfo struct {
14+
Name string
15+
ModTime time.Time
16+
}
17+
18+
// DeleteFilesWhtiKeep 删除一个目录下的文件,保留指定个数
19+
func DeleteFilesWhtiKeep(directory string, keep int) error {
20+
// 读取目录中的所有文件信息
21+
entries, err := os.ReadDir(directory)
22+
if err != nil {
23+
return fmt.Errorf("failed to read directory: %w", err)
24+
}
25+
26+
// 将文件信息存储在一个切片中
27+
var fileInfos []FileInfo
28+
for _, entry := range entries {
29+
if !entry.IsDir() {
30+
info, errInfo := entry.Info()
31+
if errInfo != nil {
32+
return fmt.Errorf("failed to get file info: %w", errInfo)
33+
}
34+
fileInfos = append(fileInfos, FileInfo{Name: entry.Name(), ModTime: info.ModTime()})
35+
}
36+
}
37+
38+
// 如果文件数量小于或等于要保留的数量,则无需删除任何文件
39+
if len(fileInfos) <= keep {
40+
return nil
41+
}
42+
43+
// 按修改时间升序排序
44+
sort.Slice(fileInfos, func(i, j int) bool {
45+
return fileInfos[i].ModTime.Before(fileInfos[j].ModTime)
46+
})
47+
48+
// 删除最早的文件,直到只剩下保留的数量
49+
for i := 0; i < len(fileInfos)-keep; i++ {
50+
errRemove := os.Remove(directory + "/" + fileInfos[i].Name)
51+
if errRemove != nil {
52+
return fmt.Errorf("failed to delete file %s: %w", fileInfos[i].Name, errRemove)
53+
}
54+
}
55+
56+
return nil
57+
}
58+
59+
// FixPath 修正路径,支持 ~
60+
func FixPath(configFilePath string) string {
61+
if strings.HasPrefix(configFilePath, "~") {
62+
homeDir, err := os.UserHomeDir()
63+
if err != nil {
64+
logrus.Warnln(err)
65+
} else {
66+
configFilePath = filepath.Join(homeDir, configFilePath[1:])
67+
}
68+
}
69+
return configFilePath
70+
}

comm/logger.go

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package comm
2+
3+
import (
4+
"fmt"
5+
"github.com/sirupsen/logrus"
6+
"os"
7+
"time"
8+
)
9+
10+
// LogSetStdout 设置日志输出为标准输出
11+
func LogSetStdout() {
12+
logSetDefault()
13+
logrus.SetOutput(os.Stdout)
14+
}
15+
16+
// LogSetFile 设置日志输出为文件
17+
func LogSetFile() {
18+
logrus.SetLevel(ShowKubeteaConfig().Log.Level)
19+
20+
// 创建日志目录
21+
dir := FixPath(ShowKubeteaConfig().Log.Dir)
22+
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
23+
logrus.Fatal(err)
24+
}
25+
26+
// 扫描目录,删除超过指定数量的日志文件
27+
errDel := DeleteFilesWhtiKeep(dir, ShowKubeteaConfig().Log.FileTotalMax)
28+
29+
// 打开日志文件
30+
logFilePath := fmt.Sprintf("%s/%s.log", dir, time.Now().Format(time.DateOnly))
31+
fo, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0664)
32+
if err != nil {
33+
if errDel != nil {
34+
logrus.WithFields(logrus.Fields{"dir": dir}).Errorln(errDel)
35+
}
36+
logrus.WithFields(logrus.Fields{"dir": dir}).Fatal(err)
37+
}
38+
39+
// 设置日志输出路径
40+
logSetDefault()
41+
logrus.SetOutput(fo)
42+
}
43+
44+
// 设置默认的日志配置
45+
func logSetDefault() {
46+
logrus.SetReportCaller(true)
47+
}

k8s/pods.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ func (p *podCache) needUpdate() bool {
103103

104104
var PodCache = sync.OnceValue(func() *podCache {
105105
c := &podCache{
106-
livetime: time.Second * time.Duration(comm.ShowKConfig().PodCacheLivetime),
106+
livetime: time.Second * time.Duration(comm.ShowKubeteaConfig().PodCacheLivetime),
107107
dataRead: make(chan bool),
108108
}
109109
return c

kubetea.yaml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,13 @@ cluster_by_label: app
55
# pod cache when x second for update
66
pod_cache_livetime_second: 5
77

8+
log:
9+
# log write level: 1 fatal, 2 error, 3 warning, 4 info, 5 debug, 6 trace
10+
level: 4
11+
dir: "~/.kubetea/log"
12+
# max log file count, delete old log file when reach this count
13+
file_total_max: 10
14+
815
# show pod group filter
916
cluster_filters:
1017
- *

main.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,13 @@ import (
1010

1111
func main() {
1212
// 日志配置
13-
logrus.SetReportCaller(true)
13+
comm.LogSetStdout()
1414

1515
// 定义入口
1616
app := &cli.App{
1717
Name: "kubernetes simple cli ui client",
1818
Flags: []cli.Flag{
19-
&cli.StringFlag{Name: "config", Aliases: []string{"c"}, Value: "~/.kube/kubetea.yaml", Usage: "(optional) path to the kubetea.yaml config file"},
19+
&cli.StringFlag{Name: "config", Aliases: []string{"c"}, Value: "~/.kubetea/config.yaml", Usage: "(optional) path to the kubetea.yaml config file"},
2020
&cli.StringFlag{Name: "namespace", Aliases: []string{"n"}},
2121
&cli.StringFlag{Name: "context"},
2222
&cli.StringFlag{Name: "kubeconfig", Aliases: []string{"k"}, Usage: "(optional) absolute path to the kubeconfig file"},

view/action.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,20 @@
11
package view
22

33
import (
4+
"github.com/flyhope/kubetea/comm"
45
"github.com/flyhope/kubetea/ui"
56
"github.com/urfave/cli/v2"
67
)
78

89
// Action 主入口
910
func Action(c *cli.Context) error {
11+
comm.LogSetFile()
12+
1013
m, err := ShowCluster()
1114
if err != nil {
1215
return err
1316
}
1417

1518
_, err = ui.RunProgram(m)
16-
return err
19+
return nil
1720
}

view/cluster.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ type clusterModel struct {
2121

2222
// 更新数据
2323
func (c *clusterModel) updateData(force bool) {
24-
config := comm.ShowKConfig()
24+
config := comm.ShowKubeteaConfig()
2525
groupLabels := make(map[string]int)
2626

2727
pods, err := k8s.PodCache().ShowList(force)

0 commit comments

Comments
 (0)