Skip to content

Commit

Permalink
feat: support log level (TencentBlueKing#57)
Browse files Browse the repository at this point in the history
* refactor: remove print code

* feat: support log level

* feat: support log level

* feat: support log level

* feat: support log level

* feat: support log level

* feat: support log level
  • Loading branch information
ifooth committed Dec 28, 2023
1 parent 742d111 commit ef2942e
Show file tree
Hide file tree
Showing 9 changed files with 118 additions and 9 deletions.
2 changes: 1 addition & 1 deletion cmd/bscp/common.go
Expand Up @@ -139,7 +139,7 @@ func initArgs() error {
}

func initFromConfig() error {
fmt.Println("use config file: ", configPath)
fmt.Println("use config file:", configPath)
v := viper.New()
v.SetConfigFile(configPath)
// 固定 yaml 格式
Expand Down
9 changes: 7 additions & 2 deletions cmd/bscp/get.go
Expand Up @@ -78,13 +78,18 @@ func init() {

// runGetApp executes the get app command.
func runGetApp(args []string) error {
// 设置日志等级, get 命令默认是 error
if logLevel == "" {
logLevel = "error"
}
level := logger.GetLevelByName(logLevel)
logger.SetLevel(level)

baseConf, err := initBaseConf()
if err != nil {
return err
}

logger.SetLevel(slog.LevelError)

bscp, err := client.New(
client.WithFeedAddrs(baseConf.GetFeedAddrs()),
client.WithBizID(baseConf.Biz),
Expand Down
4 changes: 4 additions & 0 deletions cmd/bscp/pull.go
Expand Up @@ -48,6 +48,10 @@ func Pull(cmd *cobra.Command, args []string) {
// print bscp banner
fmt.Println(strings.TrimSpace(version.GetStartInfo()))

// 设置日志等级
level := logger.GetLevelByName(logLevel)
logger.SetLevel(level)

if err := initArgs(); err != nil {
logger.Error("init", logger.ErrAttr(err))
os.Exit(1)
Expand Down
3 changes: 2 additions & 1 deletion cmd/bscp/root.go
Expand Up @@ -48,7 +48,8 @@ func init() {
rootCmd.AddCommand(PullCmd)
rootCmd.AddCommand(WatchCmd)
rootCmd.AddCommand(VersionCmd)
rootCmd.PersistentFlags().StringVarP(&logLevel, "log-level", "", "info", "log filtering level.")
rootCmd.PersistentFlags().StringVarP(
&logLevel, "log-level", "", "", "log filtering level, One of: debug|info|warn|error. (default info)")
rootCmd.PersistentFlags().StringVarP(&configPath, "config", "c", "", "config file path")

for env, f := range rootEnvs {
Expand Down
4 changes: 4 additions & 0 deletions cmd/bscp/watch.go
Expand Up @@ -55,6 +55,10 @@ func Watch(cmd *cobra.Command, args []string) {
// print bscp banner
fmt.Println(strings.TrimSpace(version.GetStartInfo()))

// 设置日志等级
level := logger.GetLevelByName(logLevel)
logger.SetLevel(level)

if err := initArgs(); err != nil {
logger.Error("init args", logger.ErrAttr(err))
os.Exit(1)
Expand Down
3 changes: 2 additions & 1 deletion examples/go.mod
Expand Up @@ -10,11 +10,12 @@ require (

require (
github.com/Tencent/bk-bcs/bcs-common v0.0.0-20230912015319-acb7495967f5 // indirect
github.com/TencentBlueking/bk-bcs/bcs-services/bcs-bscp v0.0.0-20231222100254-f7b4213bd09c // indirect
github.com/TencentBlueking/bk-bcs/bcs-services/bcs-bscp v0.0.0-20231226133937-7be33dc8c268 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/coreos/go-semver v0.3.1 // indirect
github.com/coreos/go-systemd/v22 v22.5.0 // indirect
github.com/denisbrodbeck/machineid v1.0.1 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
Expand Down
6 changes: 4 additions & 2 deletions examples/go.sum
Expand Up @@ -40,8 +40,8 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/Tencent/bk-bcs/bcs-common v0.0.0-20230912015319-acb7495967f5 h1:8B8di9Hxgh9aIIMLVkIhQnsJmAwKd1VxgjfHlvJ+864=
github.com/Tencent/bk-bcs/bcs-common v0.0.0-20230912015319-acb7495967f5/go.mod h1:/9h4LrWU1cVp46TF0DW5sUrqLtUyyMW0A9mnqhCTavA=
github.com/TencentBlueking/bk-bcs/bcs-services/bcs-bscp v0.0.0-20231222100254-f7b4213bd09c h1:dvfeBQy2X8o7kocPUyvRKYyz14bsHQ0NO16ETp3XKVI=
github.com/TencentBlueking/bk-bcs/bcs-services/bcs-bscp v0.0.0-20231222100254-f7b4213bd09c/go.mod h1:hcXljx/5UrwyWjyp1BDONJvjQvo0GDcuyvssyC53Cc8=
github.com/TencentBlueking/bk-bcs/bcs-services/bcs-bscp v0.0.0-20231226133937-7be33dc8c268 h1:+ouXa/wuA0WoYBz5EvIutaSmwJwj12HM40XC24tgNoU=
github.com/TencentBlueking/bk-bcs/bcs-services/bcs-bscp v0.0.0-20231226133937-7be33dc8c268/go.mod h1:hcXljx/5UrwyWjyp1BDONJvjQvo0GDcuyvssyC53Cc8=
github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
Expand All @@ -63,6 +63,8 @@ github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46t
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/denisbrodbeck/machineid v1.0.1 h1:geKr9qtkB876mXguW2X6TU4ZynleN6ezuMSRhl4D7AQ=
github.com/denisbrodbeck/machineid v1.0.1/go.mod h1:dJUwb7PTidGDeYyUBmXZ2GphQBbjJCrnectwCyxcUSI=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
Expand Down
18 changes: 16 additions & 2 deletions pkg/logger/logger.go
Expand Up @@ -15,7 +15,6 @@ package logger

import (
"context"
"fmt"
"os"
"path/filepath"
"runtime"
Expand Down Expand Up @@ -78,6 +77,22 @@ func SetLevel(level slog.Leveler) {
defaultLogger.Store(logger)
}

// GetLevelByName human readable logger level
func GetLevelByName(name string) slog.Leveler {
switch name {
case "error":
return slog.LevelError
case "warn":
return slog.LevelWarn
case "info":
return slog.LevelInfo
case "debug":
return slog.LevelDebug
default:
return slog.LevelInfo
}
}

// Debug logs at LevelDebug.
func Debug(msg string, args ...any) {
getLogger().Debug(msg, args...)
Expand Down Expand Up @@ -136,6 +151,5 @@ func ReplaceSourceAttr(groups []string, a slog.Attr) slog.Attr {

dir, file := filepath.Split(source.File)
source.File = filepath.Join(filepath.Base(dir), file)
fmt.Println(source)
return a
}
78 changes: 78 additions & 0 deletions pkg/logger/logger_test.go
@@ -0,0 +1,78 @@
/*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/

package logger

import (
"io"
"testing"

"golang.org/x/exp/slog"
)

func BenchmarkAtomicLogger(b *testing.B) {
textHandler := slog.NewTextHandler(io.Discard, &slog.HandlerOptions{
AddSource: true,
Level: slog.LevelInfo,
ReplaceAttr: ReplaceSourceAttr,
})
SetHandler(textHandler)

for i := 0; i < b.N; i++ {
Debug("msg")
}
}

func BenchmarkNonAtomicLogger(t *testing.B) {
textHandler := slog.NewTextHandler(io.Discard, &slog.HandlerOptions{
AddSource: true,
Level: slog.LevelInfo,
ReplaceAttr: ReplaceSourceAttr,
})

_logger := slog.New(textHandler)

for i := 0; i < t.N; i++ {
_logger.Debug("msg")
}
}

func BenchmarkAtomicLoggerParallel(b *testing.B) {
textHandler := slog.NewTextHandler(io.Discard, &slog.HandlerOptions{
AddSource: true,
Level: slog.LevelInfo,
ReplaceAttr: ReplaceSourceAttr,
})
SetHandler(textHandler)

b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
Debug("msg")
}
})
}

func BenchmarkNonAtomicLoggerParallel(b *testing.B) {
textHandler := slog.NewTextHandler(io.Discard, &slog.HandlerOptions{
AddSource: true,
Level: slog.LevelInfo,
ReplaceAttr: ReplaceSourceAttr,
})

_logger := slog.New(textHandler)

b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
_logger.Debug("msg")
}
})
}

0 comments on commit ef2942e

Please sign in to comment.