棋牌项目Go的日志打印问题
项目使用 go work
管理 模块 github.com/spf13/viper
通过 application.yml
加载配置
$ tree
.
├── README.md
├── common
│ ├── application.yml
│ ├── config
│ │ └── config.go
│ ├── go.mod
│ ├── go.sum
│ ├── logs
│ │ └── logs.go
│ └── main.go
├── config
├── connector
│ └── go.mod
├── core
│ └── go.mod
├── framework
│ └── go.mod
├── game
│ └── go.mod
├── gate
│ └── go.mod
├── go.work
├── go.work.sum
├── hall
│ └── go.mod
└── user├── app├── application.yml├── go.mod└── main.go
application.yml
配置的日志等级为 debug
appName : user
log : level : DEBUG
配置日志模块
安装日志模块: github.com/charmbracelet/log
封装日志, 以便直接调用
package logsimport ( "common/config" "os" "time" "github.com/charmbracelet/log"
) var logger * log. Loggerfunc InitLog ( appName string ) { logger = log. NewWithOptions ( os. Stderr, log. Options{ Prefix: appName, ReportTimestamp: true , TimeFormat: time. DateTime, Level: log. InfoLevel, } ) if config. Conf. Log. Level == "DEBUG" { logger. SetLevel ( log. DebugLevel) }
} func Fatal ( format string , values ... any) { if len ( values) == 0 { logger. Fatal ( format) } else { logger. Fatal ( format, values... ) }
} func Info ( format string , values ... any) { if len ( values) == 0 { logger. Fatal ( format) } else { logger. Fatalf ( format, values... ) }
} func Debug ( format string , values ... any) { if len ( values) == 0 { logger. Debug ( format) } else { logger. Debug ( format, values... ) }
} func Error ( format string , values ... any) { if len ( values) == 0 { logger. Error ( format) } else { logger. Error ( format, values... ) }
}
package mainimport ( "common/config" "common/logs" "github.com/charmbracelet/log"
) func main ( ) { config. InitConfig ( "./application.yml" ) logs. InitLog ( "test" ) log. Info ( "Hello, World!" ) log. Error ( "Hello, World!" ) log. Info ( "Hello, World!" ) a := 1 go func ( ) { log. Info ( a) } ( ) select { }
}
运行命令, 可以看到日志被打印出来