modularize logger (#94)

This commit is contained in:
UUBulb 2024-11-24 16:50:03 +08:00 committed by GitHub
parent 88efe2d1d5
commit b7bba7ed3f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 81 additions and 39 deletions

View File

@ -37,6 +37,7 @@ import (
"github.com/nezhahq/agent/cmd/agent/commands"
"github.com/nezhahq/agent/model"
fm "github.com/nezhahq/agent/pkg/fm"
"github.com/nezhahq/agent/pkg/logger"
"github.com/nezhahq/agent/pkg/monitor"
"github.com/nezhahq/agent/pkg/processgroup"
"github.com/nezhahq/agent/pkg/pty"
@ -72,6 +73,11 @@ var (
ipStatus = new(atomic.Bool)
)
var (
println = logger.DefaultLogger.Println
printf = logger.DefaultLogger.Printf
)
const (
delayWhenError = time.Second * 10 // Agent 重连间隔
networkTimeOut = time.Second * 5 // 普通网络超时
@ -374,13 +380,12 @@ func runService(action string, path string) {
}
prg.Service = s
if agentConfig.Debug {
serviceLogger, err := s.Logger(nil)
if err != nil {
printf("获取 service logger 时出错: %+v", err)
} else {
util.Logger = serviceLogger
}
serviceLogger, err := s.Logger(nil)
if err != nil {
printf("获取 service logger 时出错: %+v", err)
logger.InitDefaultLogger(agentConfig.Debug, service.ConsoleLogger)
} else {
logger.InitDefaultLogger(agentConfig.Debug, serviceLogger)
}
if action == "install" {
@ -398,7 +403,7 @@ func runService(action string, path string) {
err = s.Run()
if err != nil {
util.Logger.Error(err)
logger.DefaultLogger.Error(err)
}
}
@ -932,14 +937,6 @@ func handleFMTask(task *pb.Task) {
}
}
func println(v ...interface{}) {
util.Println(agentConfig.Debug, v...)
}
func printf(format string, v ...interface{}) {
util.Printf(agentConfig.Debug, format, v...)
}
func generateQueue(start int, size int) []int {
var result []int
for i := start; i < start+size; i++ {

62
pkg/logger/logger.go Normal file
View File

@ -0,0 +1,62 @@
package logger
import (
"fmt"
"sync"
"time"
"github.com/nezhahq/service"
)
var (
DefaultLogger = &ServiceLogger{enabled: true, logger: service.ConsoleLogger}
loggerOnce sync.Once
)
type ServiceLogger struct {
enabled bool
logger service.Logger
}
func InitDefaultLogger(enabled bool, logger service.Logger) {
loggerOnce.Do(func() {
DefaultLogger = &ServiceLogger{
enabled: enabled,
logger: logger,
}
})
}
func NewServiceLogger(enable bool, logger service.Logger) *ServiceLogger {
return &ServiceLogger{
enabled: enable,
logger: logger,
}
}
func (s *ServiceLogger) Println(v ...interface{}) {
if s.enabled {
s.logger.Infof("NEZHA@%s>> %v", time.Now().Format("2006-01-02 15:04:05"), fmt.Sprint(v...))
}
}
func (s *ServiceLogger) Printf(format string, v ...interface{}) {
if s.enabled {
s.logger.Infof("NEZHA@%s>> "+format, append([]interface{}{time.Now().Format("2006-01-02 15:04:05")}, v...)...)
}
}
func (s *ServiceLogger) Error(v ...interface{}) error {
if s.enabled {
return s.logger.Errorf("NEZHA@%s>> %v", time.Now().Format("2006-01-02 15:04:05"), fmt.Sprint(v...))
}
return nil
}
func (s *ServiceLogger) Errorf(format string, v ...interface{}) error {
if s.enabled {
return s.logger.Errorf("NEZHA@%s>> "+format, append([]interface{}{time.Now().Format("2006-01-02 15:04:05")}, v...)...)
}
return nil
}

View File

@ -11,6 +11,7 @@ import (
"github.com/shirou/gopsutil/v4/process"
"github.com/nezhahq/agent/model"
"github.com/nezhahq/agent/pkg/logger"
"github.com/nezhahq/agent/pkg/monitor/conn"
"github.com/nezhahq/agent/pkg/monitor/cpu"
"github.com/nezhahq/agent/pkg/monitor/disk"
@ -18,12 +19,13 @@ import (
"github.com/nezhahq/agent/pkg/monitor/load"
"github.com/nezhahq/agent/pkg/monitor/nic"
"github.com/nezhahq/agent/pkg/monitor/temperature"
"github.com/nezhahq/agent/pkg/util"
)
var (
Version string
agentConfig *model.AgentConfig
printf = logger.DefaultLogger.Printf
)
var (
@ -279,7 +281,3 @@ func tryStat[T any](ctx context.Context, typ uint8, f hostStateFunc[T]) T {
}
return val
}
func printf(format string, v ...interface{}) {
util.Printf(agentConfig.Debug, format, v...)
}

View File

@ -7,6 +7,7 @@ import (
"sync"
"time"
"github.com/nezhahq/agent/pkg/logger"
"github.com/nezhahq/agent/pkg/util"
pb "github.com/nezhahq/agent/proto"
)
@ -25,7 +26,7 @@ var (
// UpdateIP 按设置时间间隔更新IP地址的缓存
func FetchIP(useIPv6CountryCode bool) *pb.GeoIP {
util.Println(agentConfig.Debug, "正在更新本地缓存IP信息")
logger.DefaultLogger.Println("正在更新本地缓存IP信息")
wg := new(sync.WaitGroup)
wg.Add(2)
var ipv4, ipv6 string

View File

@ -1,39 +1,23 @@
package util
import (
"fmt"
"net/http"
"os"
"strings"
"time"
jsoniter "github.com/json-iterator/go"
"github.com/nezhahq/service"
)
const MacOSChromeUA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
var (
Json = jsoniter.ConfigCompatibleWithStandardLibrary
Logger service.Logger = service.ConsoleLogger
Json = jsoniter.ConfigCompatibleWithStandardLibrary
)
func IsWindows() bool {
return os.PathSeparator == '\\' && os.PathListSeparator == ';'
}
func Println(enabled bool, v ...interface{}) {
if enabled {
Logger.Infof("NEZHA@%s>> %v", time.Now().Format("2006-01-02 15:04:05"), fmt.Sprint(v...))
}
}
func Printf(enabled bool, format string, v ...interface{}) {
if enabled {
Logger.Infof("NEZHA@%s>> "+format, append([]interface{}{time.Now().Format("2006-01-02 15:04:05")}, v...)...)
}
}
func BrowserHeaders() http.Header {
return http.Header{
"Accept": {"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"},