feat: Using logging module

This commit is contained in:
Muyao CHEN 2024-10-01 23:52:59 +02:00
parent 04fceee835
commit 08e2d6bd4a
3 changed files with 36 additions and 7 deletions

View File

@ -35,3 +35,14 @@ db:
max-open-connections: 100
# max connection life time
max-connection-life-time: 10s
log:
level: debug
development: true
disalbe-caller: false
disable-stacktrace: false
# console or json
format: console
output-paths:
- stdout
- /tmp/howmuch.log

View File

@ -23,11 +23,11 @@
package howmuch
import (
"fmt"
"os"
"path/filepath"
"strings"
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
@ -64,8 +64,20 @@ func initConfig() {
viper.SetEnvKeyReplacer(replacer)
if err := viper.ReadInConfig(); err != nil {
fmt.Fprintln(os.Stderr, err)
log.ErrorLog("Failed to read viper configuration file", "err", err)
}
fmt.Fprintln(os.Stdout, "Using config file:", viper.ConfigFileUsed())
log.InfoLog("Using config file", "file", viper.ConfigFileUsed())
}
// logOptions set log options from the configs read by viper.
func logOptions() *log.Options {
return &log.Options{
Level: viper.GetString("log.level"),
Development: viper.GetBool("log.development"),
DisableCaller: viper.GetBool("log.disable-caller"),
DisableStacktrace: viper.GetBool("log.disable-stacktrace"),
Format: viper.GetString("log.format"),
OutputPaths: viper.GetStringSlice("log.output-paths"),
}
}

View File

@ -27,6 +27,7 @@ import (
"fmt"
"net/http"
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/log"
"github.com/fsnotify/fsnotify"
"github.com/gin-gonic/gin"
"github.com/spf13/cobra"
@ -47,6 +48,11 @@ func NewHowMuchCommand() *cobra.Command {
Long: `howmuch is a expense-sharing application that can help friends
to share their expense of an event or a trip`,
RunE: func(cmd *cobra.Command, args []string) error {
// init log
log.Init(logOptions())
// Sync flush the buffer
defer log.Sync()
return run()
},
Args: func(cmd *cobra.Command, args []string) error {
@ -76,18 +82,18 @@ to share their expense of an event or a trip`,
}
func run() error {
fmt.Println("How much do I owe you?")
log.DebugLog("How much do I owe you?")
settings, _ := json.MarshalIndent(viper.AllSettings(), "", " ")
// watching reloading conf
viper.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("Config file changed:", e.Name)
log.InfoLog("Config file changed:", e.Name)
})
viper.WatchConfig()
fmt.Println(string(settings))
fmt.Println(viper.GetString("db.username"))
log.InfoLog(string(settings))
log.InfoLog(viper.GetString("db.username"))
r := gin.Default()