feat: add logging and collector implementations
- Introduced `hertzx` package with `NewHertz` function for server initialization. - Implemented `logx` package with various log collectors: Console, Loki, Elasticsearch, and Prometheus. - Added `Logger` struct to manage logging levels and collectors. - Created environment variable loading functionality in `osx` package to support configuration. - Enhanced logging capabilities with structured log entries and asynchronous collection.
This commit is contained in:
78
osx/osx.go
Normal file
78
osx/osx.go
Normal file
@@ -0,0 +1,78 @@
|
||||
package osx
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
)
|
||||
|
||||
func init() {
|
||||
// 读取目录下的所有 .env 文件,加载环境变量
|
||||
// 生产环境由于部署在kubernetes等平台,通常会直接通过环境变量注入配置
|
||||
// 因此这里的加载主要用于开发环境
|
||||
loadDotEnvFiles()
|
||||
}
|
||||
|
||||
func GetEnv(key string, defaultValue ...string) string {
|
||||
if value, exists := os.LookupEnv(key); exists {
|
||||
return value
|
||||
}
|
||||
if len(defaultValue) > 0 {
|
||||
return defaultValue[0]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetEnvInt(key string, defaultValue int) int {
|
||||
if valueStr, exists := os.LookupEnv(key); exists {
|
||||
var value int
|
||||
_, err := fmt.Sscanf(valueStr, "%d", &value)
|
||||
if err == nil {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
// GetEnvBool 支持 "true", "1", "True", "TRUE" 返回 true
|
||||
// 支持 "false", "0", "False", "FALSE" 返回 false
|
||||
// 如果环境变量不存在或无法解析,则返回 defaultValue
|
||||
func GetEnvBool(key string, defaultValue bool) bool {
|
||||
if valueStr, exists := os.LookupEnv(key); exists {
|
||||
switch valueStr {
|
||||
case "true", "1", "True", "TRUE":
|
||||
return true
|
||||
case "false", "0", "False", "FALSE":
|
||||
return false
|
||||
}
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
func GetEnvT[T any](key string, parser func(string) (T, error), defaultValue T) T {
|
||||
if valueStr, exists := os.LookupEnv(key); exists {
|
||||
if value, err := parser(valueStr); err == nil {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
func loadDotEnvFiles() {
|
||||
dotEnvFiles := []string{".env.local", ".env", ".env.development", ".env.production"}
|
||||
existedFiles := []string{}
|
||||
for _, file := range dotEnvFiles {
|
||||
if _, err := os.Stat(file); err == nil {
|
||||
existedFiles = append(existedFiles, file)
|
||||
}
|
||||
}
|
||||
if len(existedFiles) == 0 {
|
||||
return
|
||||
}
|
||||
// 按顺序加载,后面的会覆盖前面的
|
||||
err := godotenv.Load(existedFiles...)
|
||||
if err != nil {
|
||||
fmt.Printf("Error loading .env files: %v\n", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user