diff --git a/agent/cmd/main.go b/agent/cmd/main.go index 7c891b8..d2167b6 100644 --- a/agent/cmd/main.go +++ b/agent/cmd/main.go @@ -1,11 +1,14 @@ package main import ( + "os" + + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/agent/pkg/agent" "github.com/yusing/go-proxy/agent/pkg/env" "github.com/yusing/go-proxy/agent/pkg/server" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/metrics/systeminfo" httpServer "github.com/yusing/go-proxy/internal/net/gphttp/server" "github.com/yusing/go-proxy/internal/task" @@ -14,6 +17,12 @@ import ( ) func main() { + writer := zerolog.ConsoleWriter{ + Out: os.Stderr, + TimeFormat: "01-02 15:04", + } + zerolog.TimeFieldFormat = writer.TimeFormat + log.Logger = zerolog.New(writer).Level(zerolog.InfoLevel).With().Timestamp().Logger() ca := &agent.PEMPair{} err := ca.Load(env.AgentCACert) if err != nil { @@ -34,11 +43,11 @@ func main() { gperr.LogFatal("init SSL error", err) } - logging.Info().Msgf("GoDoxy Agent version %s", pkg.GetVersion()) - logging.Info().Msgf("Agent name: %s", env.AgentName) - logging.Info().Msgf("Agent port: %d", env.AgentPort) + log.Info().Msgf("GoDoxy Agent version %s", pkg.GetVersion()) + log.Info().Msgf("Agent name: %s", env.AgentName) + log.Info().Msgf("Agent port: %d", env.AgentPort) - logging.Info().Msg(` + log.Info().Msg(` Tips: 1. To change the agent name, you can set the AGENT_NAME environment variable. 2. To change the agent port, you can set the AGENT_PORT environment variable. @@ -54,7 +63,7 @@ Tips: server.StartAgentServer(t, opts) if socketproxy.ListenAddr != "" { - logging.Info().Msgf("Docker socket listening on: %s", socketproxy.ListenAddr) + log.Info().Msgf("Docker socket listening on: %s", socketproxy.ListenAddr) opts := httpServer.Options{ Name: "docker", HTTPAddr: socketproxy.ListenAddr, diff --git a/agent/pkg/agent/config.go b/agent/pkg/agent/config.go index 9840486..5887a66 100644 --- a/agent/pkg/agent/config.go +++ b/agent/pkg/agent/config.go @@ -15,8 +15,8 @@ import ( "time" "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/agent/pkg/certs" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/pkg" ) @@ -115,7 +115,7 @@ func (cfg *AgentConfig) StartWithCerts(ctx context.Context, ca, crt, key []byte) cfg.name = string(name) - cfg.l = logging.With().Str("agent", cfg.name).Logger() + cfg.l = log.With().Str("agent", cfg.name).Logger() // check agent version agentVersionBytes, _, err := cfg.Fetch(ctx, EndpointVersion) @@ -127,10 +127,10 @@ func (cfg *AgentConfig) StartWithCerts(ctx context.Context, ca, crt, key []byte) agentVersion := pkg.ParseVersion(cfg.version) if serverVersion.IsNewerMajorThan(agentVersion) { - logging.Warn().Msgf("agent %s major version mismatch: server: %s, agent: %s", cfg.name, serverVersion, agentVersion) + log.Warn().Msgf("agent %s major version mismatch: server: %s, agent: %s", cfg.name, serverVersion, agentVersion) } - logging.Info().Msgf("agent %q initialized", cfg.name) + log.Info().Msgf("agent %q initialized", cfg.name) return nil } diff --git a/agent/pkg/server/server.go b/agent/pkg/server/server.go index 9be4631..4b9e2b7 100644 --- a/agent/pkg/server/server.go +++ b/agent/pkg/server/server.go @@ -6,9 +6,9 @@ import ( "fmt" "net/http" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/agent/pkg/env" "github.com/yusing/go-proxy/agent/pkg/handler" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/net/gphttp/server" "github.com/yusing/go-proxy/internal/task" ) @@ -33,12 +33,11 @@ func StartAgentServer(parent task.Parent, opt Options) { tlsConfig.ClientAuth = tls.NoClientCert } - logger := logging.GetLogger() agentServer := &http.Server{ Addr: fmt.Sprintf(":%d", opt.Port), Handler: handler.NewAgentHandler(), TLSConfig: tlsConfig, } - server.Start(parent, agentServer, nil, logger) + server.Start(parent, agentServer, nil, &log.Logger) } diff --git a/cmd/main.go b/cmd/main.go index 125ec69..c2cb3c1 100755 --- a/cmd/main.go +++ b/cmd/main.go @@ -4,6 +4,7 @@ import ( "os" "sync" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/auth" "github.com/yusing/go-proxy/internal/common" "github.com/yusing/go-proxy/internal/config" @@ -35,8 +36,8 @@ func main() { initProfiling() logging.InitLogger(os.Stderr, memlogger.GetMemLogger()) - logging.Info().Msgf("GoDoxy version %s", pkg.GetVersion()) - logging.Trace().Msg("trace enabled") + log.Info().Msgf("GoDoxy version %s", pkg.GetVersion()) + log.Trace().Msg("trace enabled") parallel( dnsproviders.InitProviders, homepage.InitIconListCache, @@ -45,7 +46,7 @@ func main() { ) if common.APIJWTSecret == nil { - logging.Warn().Msg("API_JWT_SECRET is not set, using random key") + log.Warn().Msg("API_JWT_SECRET is not set, using random key") common.APIJWTSecret = common.RandomJWTKey() } @@ -62,7 +63,7 @@ func main() { Proxy: true, }) if err := auth.Initialize(); err != nil { - logging.Fatal().Err(err).Msg("failed to initialize authentication") + log.Fatal().Err(err).Msg("failed to initialize authentication") } // API Handler needs to start after auth is initialized. cfg.StartServers(&config.StartServersOptions{ @@ -78,7 +79,7 @@ func main() { func prepareDirectory(dir string) { if _, err := os.Stat(dir); os.IsNotExist(err) { if err = os.MkdirAll(dir, 0o755); err != nil { - logging.Fatal().Msgf("failed to create directory %s: %v", dir, err) + log.Fatal().Msgf("failed to create directory %s: %v", dir, err) } } } diff --git a/internal/acl/config.go b/internal/acl/config.go index 2b7c5ef..fe06d47 100644 --- a/internal/acl/config.go +++ b/internal/acl/config.go @@ -5,9 +5,9 @@ import ( "time" "github.com/puzpuzpuz/xsync/v4" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/common" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/logging/accesslog" "github.com/yusing/go-proxy/internal/maxmind" "github.com/yusing/go-proxy/internal/task" @@ -97,7 +97,7 @@ func (c *Config) Start(parent *task.Task) gperr.Error { if c.valErr != nil { return c.valErr } - logging.Info(). + log.Info(). Str("default", c.Default). Bool("allow_local", c.allowLocal). Int("allow_rules", len(c.Allow)). diff --git a/internal/api/v1/certapi/renew.go b/internal/api/v1/certapi/renew.go index b274ef4..084db82 100644 --- a/internal/api/v1/certapi/renew.go +++ b/internal/api/v1/certapi/renew.go @@ -3,9 +3,9 @@ package certapi import ( "net/http" + "github.com/rs/zerolog/log" config "github.com/yusing/go-proxy/internal/config/types" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/logging/memlogger" "github.com/yusing/go-proxy/internal/net/gphttp/gpwebsocket" ) @@ -36,7 +36,7 @@ func RenewCert(w http.ResponseWriter, r *http.Request) { gperr.LogError("failed to obtain cert", err) _ = gpwebsocket.WriteText(conn, err.Error()) } else { - logging.Info().Msg("cert obtained successfully") + log.Info().Msg("cert obtained successfully") } }() for { diff --git a/internal/api/v1/dockerapi/logs.go b/internal/api/v1/dockerapi/logs.go index 916fa3f..c313fed 100644 --- a/internal/api/v1/dockerapi/logs.go +++ b/internal/api/v1/dockerapi/logs.go @@ -9,7 +9,7 @@ import ( "github.com/docker/docker/api/types/container" "github.com/docker/docker/pkg/stdcopy" "github.com/gorilla/websocket" - "github.com/yusing/go-proxy/internal/logging" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/net/gphttp" "github.com/yusing/go-proxy/internal/net/gphttp/gpwebsocket" "github.com/yusing/go-proxy/internal/task" @@ -69,7 +69,7 @@ func Logs(w http.ResponseWriter, r *http.Request) { if errors.Is(err, context.Canceled) || errors.Is(err, task.ErrProgramExiting) { return } - logging.Err(err). + log.Err(err). Str("server", server). Str("container", containerID). Msg("failed to de-multiplex logs") diff --git a/internal/auth/oauth_refresh.go b/internal/auth/oauth_refresh.go index 5d3d022..fd14332 100644 --- a/internal/auth/oauth_refresh.go +++ b/internal/auth/oauth_refresh.go @@ -11,9 +11,9 @@ import ( "time" "github.com/golang-jwt/jwt/v5" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/common" "github.com/yusing/go-proxy/internal/jsonstore" - "github.com/yusing/go-proxy/internal/logging" "golang.org/x/oauth2" ) @@ -108,11 +108,11 @@ func storeOAuthRefreshToken(sessionID sessionID, username, token string) { RefreshToken: token, Expiry: time.Now().Add(defaultRefreshTokenExpiry), }) - logging.Debug().Str("username", username).Msg("stored oauth refresh token") + log.Debug().Str("username", username).Msg("stored oauth refresh token") } func invalidateOAuthRefreshToken(sessionID sessionID) { - logging.Debug().Str("session_id", string(sessionID)).Msg("invalidating oauth refresh token") + log.Debug().Str("session_id", string(sessionID)).Msg("invalidating oauth refresh token") oauthRefreshTokens.Delete(string(sessionID)) } @@ -127,7 +127,7 @@ func (auth *OIDCProvider) setSessionTokenCookie(w http.ResponseWriter, r *http.R jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS512, claims) signed, err := jwtToken.SignedString(common.APIJWTSecret) if err != nil { - logging.Err(err).Msg("failed to sign session token") + log.Err(err).Msg("failed to sign session token") return } SetTokenCookie(w, r, CookieOauthSessionToken, signed, common.APIJWTTokenTTL) @@ -205,7 +205,7 @@ func (auth *OIDCProvider) doRefreshToken(ctx context.Context, refreshToken *oaut sessionID := newSessionID() - logging.Debug().Str("username", claims.Username).Time("expiry", newToken.Expiry).Msg("refreshed token") + log.Debug().Str("username", claims.Username).Time("expiry", newToken.Expiry).Msg("refreshed token") storeOAuthRefreshToken(sessionID, claims.Username, newToken.RefreshToken) refreshToken.result = &RefreshResult{ diff --git a/internal/auth/oidc.go b/internal/auth/oidc.go index 4c8c0b2..0b0afc2 100644 --- a/internal/auth/oidc.go +++ b/internal/auth/oidc.go @@ -12,9 +12,9 @@ import ( "time" "github.com/coreos/go-oidc/v3/oidc" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/common" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/net/gphttp" "github.com/yusing/go-proxy/internal/utils" "golang.org/x/oauth2" @@ -79,7 +79,7 @@ func NewOIDCProvider(issuerURL, clientID, clientSecret string, allowedUsers, all endSessionURL, err := url.Parse(provider.EndSessionEndpoint()) if err != nil && provider.EndSessionEndpoint() != "" { // non critical, just warn - logging.Warn(). + log.Warn(). Str("issuer", issuerURL). Err(err). Msg("failed to parse end session URL") @@ -176,7 +176,7 @@ func (auth *OIDCProvider) LoginHandler(w http.ResponseWriter, r *http.Request) { return } // clear cookies then redirect to home - logging.Err(err).Msg("failed to refresh token") + log.Err(err).Msg("failed to refresh token") auth.clearCookie(w, r) http.Redirect(w, r, "/", http.StatusFound) return diff --git a/internal/autocert/config.go b/internal/autocert/config.go index 0934d96..52d00e0 100644 --- a/internal/autocert/config.go +++ b/internal/autocert/config.go @@ -10,8 +10,8 @@ import ( "github.com/go-acme/lego/v4/certcrypto" "github.com/go-acme/lego/v4/lego" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/utils" ) @@ -100,8 +100,8 @@ func (cfg *Config) GetLegoConfig() (*User, *lego.Config, gperr.Error) { if cfg.Provider != ProviderLocal && cfg.Provider != ProviderPseudo { if privKey, err = cfg.LoadACMEKey(); err != nil { - logging.Info().Err(err).Msg("load ACME private key failed") - logging.Info().Msg("generate new ACME private key") + log.Info().Err(err).Msg("load ACME private key failed") + log.Info().Msg("generate new ACME private key") privKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { return nil, nil, gperr.New("generate ACME private key").With(err) diff --git a/internal/autocert/provider.go b/internal/autocert/provider.go index 8c2585b..a269924 100644 --- a/internal/autocert/provider.go +++ b/internal/autocert/provider.go @@ -15,8 +15,8 @@ import ( "github.com/go-acme/lego/v4/lego" "github.com/go-acme/lego/v4/registration" "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/notif" "github.com/yusing/go-proxy/internal/task" "github.com/yusing/go-proxy/internal/utils/strutils" @@ -78,11 +78,11 @@ func (p *Provider) ObtainCert() error { if p.cfg.Provider == ProviderPseudo { t := time.NewTicker(1000 * time.Millisecond) defer t.Stop() - logging.Info().Msg("init client for pseudo provider") + log.Info().Msg("init client for pseudo provider") <-t.C - logging.Info().Msg("registering acme for pseudo provider") + log.Info().Msg("registering acme for pseudo provider") <-t.C - logging.Info().Msg("obtained cert for pseudo provider") + log.Info().Msg("obtained cert for pseudo provider") return nil } @@ -107,7 +107,7 @@ func (p *Provider) ObtainCert() error { }) if err != nil { p.legoCert = nil - logging.Err(err).Msg("cert renew failed, fallback to obtain") + log.Err(err).Msg("cert renew failed, fallback to obtain") } else { p.legoCert = cert } @@ -154,7 +154,7 @@ func (p *Provider) LoadCert() error { p.tlsCert = &cert p.certExpiries = expiries - logging.Info().Msgf("next renewal in %v", strutils.FormatDuration(time.Until(p.ShouldRenewOn()))) + log.Info().Msgf("next renewal in %v", strutils.FormatDuration(time.Until(p.ShouldRenewOn()))) return p.renewIfNeeded() } @@ -240,7 +240,7 @@ func (p *Provider) registerACME() error { } if reg, err := p.client.Registration.ResolveAccountByKey(); err == nil { p.user.Registration = reg - logging.Info().Msg("reused acme registration from private key") + log.Info().Msg("reused acme registration from private key") return nil } @@ -249,7 +249,7 @@ func (p *Provider) registerACME() error { return err } p.user.Registration = reg - logging.Info().Interface("reg", reg).Msg("acme registered") + log.Info().Interface("reg", reg).Msg("acme registered") return nil } @@ -295,7 +295,7 @@ func (p *Provider) certState() CertState { sort.Strings(certDomains) if !reflect.DeepEqual(certDomains, wantedDomains) { - logging.Info().Msgf("cert domains mismatch: %v != %v", certDomains, p.cfg.Domains) + log.Info().Msgf("cert domains mismatch: %v != %v", certDomains, p.cfg.Domains) return CertStateMismatch } @@ -309,9 +309,9 @@ func (p *Provider) renewIfNeeded() error { switch p.certState() { case CertStateExpired: - logging.Info().Msg("certs expired, renewing") + log.Info().Msg("certs expired, renewing") case CertStateMismatch: - logging.Info().Msg("cert domains mismatch with config, renewing") + log.Info().Msg("cert domains mismatch with config, renewing") default: return nil } diff --git a/internal/autocert/setup.go b/internal/autocert/setup.go index b436bed..62c589e 100644 --- a/internal/autocert/setup.go +++ b/internal/autocert/setup.go @@ -4,7 +4,7 @@ import ( "errors" "os" - "github.com/yusing/go-proxy/internal/logging" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/utils/strutils" ) @@ -13,14 +13,14 @@ func (p *Provider) Setup() (err error) { if !errors.Is(err, os.ErrNotExist) { // ignore if cert doesn't exist return err } - logging.Debug().Msg("obtaining cert due to error loading cert") + log.Debug().Msg("obtaining cert due to error loading cert") if err = p.ObtainCert(); err != nil { return err } } for _, expiry := range p.GetExpiries() { - logging.Info().Msg("certificate expire on " + strutils.FormatTime(expiry)) + log.Info().Msg("certificate expire on " + strutils.FormatTime(expiry)) break } diff --git a/internal/config/config.go b/internal/config/config.go index 6ae6b55..02cac28 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -10,13 +10,13 @@ import ( "time" "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/api" autocert "github.com/yusing/go-proxy/internal/autocert" "github.com/yusing/go-proxy/internal/common" config "github.com/yusing/go-proxy/internal/config/types" "github.com/yusing/go-proxy/internal/entrypoint" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/maxmind" "github.com/yusing/go-proxy/internal/net/gphttp/server" "github.com/yusing/go-proxy/internal/notif" @@ -96,10 +96,10 @@ func OnConfigChange(ev []events.Event) { // just reload once and check the last event switch ev[len(ev)-1].Action { case events.ActionFileRenamed: - logging.Warn().Msg(cfgRenameWarn) + log.Warn().Msg(cfgRenameWarn) return case events.ActionFileDeleted: - logging.Warn().Msg(cfgDeleteWarn) + log.Warn().Msg(cfgDeleteWarn) return } @@ -161,7 +161,7 @@ func (cfg *Config) Start(opts ...*StartServersOptions) { func (cfg *Config) StartAutoCert() { autocert := cfg.autocertProvider if autocert == nil { - logging.Info().Msg("autocert not configured") + log.Info().Msg("autocert not configured") return } @@ -374,6 +374,6 @@ func (cfg *Config) loadRouteProviders(providers *config.Providers) gperr.Error { } results.Addf("%-"+strconv.Itoa(lenLongestName)+"s %d routes", p.String(), p.NumRoutes()) }) - logging.Info().Msg(results.String()) + log.Info().Msg(results.String()) return errs.Error() } diff --git a/internal/docker/client.go b/internal/docker/client.go index 7e1b892..3c78806 100644 --- a/internal/docker/client.go +++ b/internal/docker/client.go @@ -13,10 +13,10 @@ import ( "github.com/docker/cli/cli/connhelper" "github.com/docker/docker/client" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/agent/pkg/agent" "github.com/yusing/go-proxy/internal/common" config "github.com/yusing/go-proxy/internal/config/types" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/task" ) @@ -84,7 +84,7 @@ func closeTimedOutClients() { if atomic.LoadUint32(&c.refCount) == 0 && now-atomic.LoadInt64(&c.closedOn) > clientTTLSecs { delete(clientMap, c.Key()) c.Client.Close() - logging.Debug().Str("host", c.DaemonHost()).Msg("docker client closed") + log.Debug().Str("host", c.DaemonHost()).Msg("docker client closed") } } } @@ -149,7 +149,7 @@ func NewClient(host string) (*SharedClient, error) { default: helper, err := connhelper.GetConnectionHelper(host) if err != nil { - logging.Panic().Err(err).Msg("failed to get connection helper") + log.Panic().Err(err).Msg("failed to get connection helper") } if helper != nil { httpClient := &http.Client{ @@ -193,7 +193,7 @@ func NewClient(host string) (*SharedClient, error) { c.addr = c.Client.DaemonHost() } - defer logging.Debug().Str("host", host).Msg("docker client initialized") + defer log.Debug().Str("host", host).Msg("docker client initialized") clientMap[c.Key()] = c return c, nil diff --git a/internal/docker/container.go b/internal/docker/container.go index 07d07be..ddc4ac6 100644 --- a/internal/docker/container.go +++ b/internal/docker/container.go @@ -9,11 +9,11 @@ import ( "github.com/docker/docker/api/types/container" "github.com/docker/go-connections/nat" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/agent/pkg/agent" config "github.com/yusing/go-proxy/internal/config/types" "github.com/yusing/go-proxy/internal/gperr" idlewatcher "github.com/yusing/go-proxy/internal/idlewatcher/types" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/serialization" "github.com/yusing/go-proxy/internal/utils" ) @@ -91,7 +91,7 @@ func FromDocker(c *container.SummaryTrimmed, dockerHost string) (res *Container) var ok bool res.Agent, ok = config.GetInstance().GetAgent(dockerHost) if !ok { - logging.Error().Msgf("agent %q not found", dockerHost) + log.Error().Msgf("agent %q not found", dockerHost) } } @@ -184,7 +184,7 @@ func (c *Container) setPublicHostname() { } url, err := url.Parse(c.DockerHost) if err != nil { - logging.Err(err).Msgf("invalid docker host %q, falling back to 127.0.0.1", c.DockerHost) + log.Err(err).Msgf("invalid docker host %q, falling back to 127.0.0.1", c.DockerHost) c.PublicHostname = "127.0.0.1" return } diff --git a/internal/entrypoint/entrypoint.go b/internal/entrypoint/entrypoint.go index e3683db..aa35b9c 100644 --- a/internal/entrypoint/entrypoint.go +++ b/internal/entrypoint/entrypoint.go @@ -6,7 +6,7 @@ import ( "net/http" "strings" - "github.com/yusing/go-proxy/internal/logging" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/logging/accesslog" gphttp "github.com/yusing/go-proxy/internal/net/gphttp" "github.com/yusing/go-proxy/internal/net/gphttp/middleware" @@ -50,7 +50,7 @@ func (ep *Entrypoint) SetMiddlewares(mws []map[string]any) error { } ep.middleware = mid - logging.Debug().Msg("entrypoint middleware loaded") + log.Debug().Msg("entrypoint middleware loaded") return nil } @@ -64,7 +64,7 @@ func (ep *Entrypoint) SetAccessLogger(parent task.Parent, cfg *accesslog.Request if err != nil { return } - logging.Debug().Msg("entrypoint access logger created") + log.Debug().Msg("entrypoint access logger created") return } @@ -89,7 +89,7 @@ func (ep *Entrypoint) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Then scraper / scanners will know the subdomain is invalid. // With StatusNotFound, they won't know whether it's the path, or the subdomain that is invalid. if served := middleware.ServeStaticErrorPageFile(w, r); !served { - logging.Err(err). + log.Err(err). Str("method", r.Method). Str("url", r.URL.String()). Str("remote", r.RemoteAddr). @@ -99,7 +99,7 @@ func (ep *Entrypoint) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) w.Header().Set("Content-Type", "text/html; charset=utf-8") if _, err := w.Write(errorPage); err != nil { - logging.Err(err).Msg("failed to write error page") + log.Err(err).Msg("failed to write error page") } } else { http.Error(w, err.Error(), http.StatusNotFound) diff --git a/internal/gperr/log.go b/internal/gperr/log.go index 5be1bce..a13336b 100644 --- a/internal/gperr/log.go +++ b/internal/gperr/log.go @@ -4,8 +4,8 @@ import ( "os" "github.com/rs/zerolog" + zerologlog "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/common" - "github.com/yusing/go-proxy/internal/logging" ) func log(msg string, err error, level zerolog.Level, logger ...*zerolog.Logger) { @@ -13,7 +13,7 @@ func log(msg string, err error, level zerolog.Level, logger ...*zerolog.Logger) if len(logger) > 0 { l = logger[0] } else { - l = logging.GetLogger() + l = &zerologlog.Logger } l.WithLevel(level).Msg(New(highlightANSI(msg)).With(err).Error()) switch level { diff --git a/internal/homepage/icon_cache.go b/internal/homepage/icon_cache.go index 4f0f658..2a4f5c2 100644 --- a/internal/homepage/icon_cache.go +++ b/internal/homepage/icon_cache.go @@ -6,9 +6,9 @@ import ( "sync" "time" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/common" "github.com/yusing/go-proxy/internal/jsonstore" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/task" "github.com/yusing/go-proxy/internal/utils" "github.com/yusing/go-proxy/internal/utils/atomic" @@ -74,7 +74,7 @@ func pruneExpiredIconCache() { } } if nPruned > 0 { - logging.Info().Int("pruned", nPruned).Msg("pruned expired icon cache") + log.Info().Int("pruned", nPruned).Msg("pruned expired icon cache") } } @@ -87,7 +87,7 @@ func loadIconCache(key string) *FetchResult { defer iconMu.RUnlock() icon, ok := iconCache.Load(key) if ok && len(icon.Icon) > 0 { - logging.Debug(). + log.Debug(). Str("key", key). Msg("icon found in cache") icon.LastAccess.Store(utils.TimeNow()) @@ -99,7 +99,7 @@ func loadIconCache(key string) *FetchResult { func storeIconCache(key string, result *FetchResult) { icon := result.Icon if len(icon) > maxIconSize { - logging.Debug().Int("size", len(icon)).Msg("icon cache size exceeds max cache size") + log.Debug().Int("size", len(icon)).Msg("icon cache size exceeds max cache size") return } @@ -109,7 +109,7 @@ func storeIconCache(key string, result *FetchResult) { entry := &cacheEntry{Icon: icon, ContentType: result.contentType} entry.LastAccess.Store(time.Now()) iconCache.Store(key, entry) - logging.Debug().Str("key", key).Int("size", len(icon)).Msg("stored icon cache") + log.Debug().Str("key", key).Int("size", len(icon)).Msg("stored icon cache") } func (e *cacheEntry) IsExpired() bool { diff --git a/internal/homepage/list_icons.go b/internal/homepage/list_icons.go index cb96ba8..2c3d2cf 100644 --- a/internal/homepage/list_icons.go +++ b/internal/homepage/list_icons.go @@ -10,8 +10,8 @@ import ( "time" "github.com/lithammer/fuzzysearch/fuzzy" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/common" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/serialization" "github.com/yusing/go-proxy/internal/task" "github.com/yusing/go-proxy/internal/utils/strutils" @@ -101,15 +101,15 @@ func InitIconListCache() { err := serialization.LoadJSONIfExist(common.IconListCachePath, iconsCache) if err != nil { - logging.Error().Err(err).Msg("failed to load icons") + log.Error().Err(err).Msg("failed to load icons") } else if len(iconsCache.Icons) > 0 { - logging.Info(). + log.Info(). Int("icons", len(iconsCache.Icons)). Msg("icons loaded") } if err = updateIcons(); err != nil { - logging.Error().Err(err).Msg("failed to update icons") + log.Error().Err(err).Msg("failed to update icons") } task.OnProgramExit("save_icons_cache", func() { @@ -134,17 +134,17 @@ func ListAvailableIcons() (*Cache, error) { iconsCache.Lock() defer iconsCache.Unlock() - logging.Info().Msg("updating icon data") + log.Info().Msg("updating icon data") if err := updateIcons(); err != nil { return nil, err } - logging.Info().Int("icons", len(iconsCache.Icons)).Msg("icons list updated") + log.Info().Int("icons", len(iconsCache.Icons)).Msg("icons list updated") iconsCache.LastUpdate = time.Now() err := serialization.SaveJSON(common.IconListCachePath, iconsCache, 0o644) if err != nil { - logging.Warn().Err(err).Msg("failed to save icons") + log.Warn().Err(err).Msg("failed to save icons") } return iconsCache, nil } diff --git a/internal/idlewatcher/watcher.go b/internal/idlewatcher/watcher.go index 02f84e1..5d79832 100644 --- a/internal/idlewatcher/watcher.go +++ b/internal/idlewatcher/watcher.go @@ -7,10 +7,10 @@ import ( "time" "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/gperr" "github.com/yusing/go-proxy/internal/idlewatcher/provider" idlewatcher "github.com/yusing/go-proxy/internal/idlewatcher/types" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/net/gphttp/reverseproxy" net "github.com/yusing/go-proxy/internal/net/types" "github.com/yusing/go-proxy/internal/route/routes" @@ -120,7 +120,7 @@ func NewWatcher(parent task.Parent, r routes.Route) (*Watcher, error) { return nil, err } w.provider = p - w.l = logging.With(). + w.l = log.With(). Str("provider", providerType). Str("container", cfg.ContainerName()). Logger() diff --git a/internal/jsonstore/jsonstore.go b/internal/jsonstore/jsonstore.go index cf7c036..25a7506 100644 --- a/internal/jsonstore/jsonstore.go +++ b/internal/jsonstore/jsonstore.go @@ -9,9 +9,9 @@ import ( "maps" "github.com/puzpuzpuz/xsync/v4" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/common" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/serialization" "github.com/yusing/go-proxy/internal/task" ) @@ -42,7 +42,7 @@ var storesPath = common.DataDir func init() { task.OnProgramExit("save_stores", func() { if err := save(); err != nil { - logging.Error().Err(err).Msg("failed to save stores") + log.Error().Err(err).Msg("failed to save stores") } }) } @@ -54,20 +54,20 @@ func loadNS[T store](ns namespace) T { file, err := os.Open(path) if err != nil { if !os.IsNotExist(err) { - logging.Err(err). + log.Err(err). Str("path", path). Msg("failed to load store") } } else { defer file.Close() if err := json.NewDecoder(file).Decode(&store); err != nil { - logging.Err(err). + log.Err(err). Str("path", path). Msg("failed to load store") } } stores[ns] = store - logging.Debug(). + log.Debug(). Str("namespace", string(ns)). Str("path", path). Msg("loaded store") @@ -86,7 +86,7 @@ func save() error { func Store[VT any](namespace namespace) MapStore[VT] { if _, ok := stores[namespace]; ok { - logging.Fatal().Str("namespace", string(namespace)).Msg("namespace already exists") + log.Fatal().Str("namespace", string(namespace)).Msg("namespace already exists") } store := loadNS[*MapStore[VT]](namespace) stores[namespace] = store @@ -95,7 +95,7 @@ func Store[VT any](namespace namespace) MapStore[VT] { func Object[Ptr Initializer](namespace namespace) Ptr { if _, ok := stores[namespace]; ok { - logging.Fatal().Str("namespace", string(namespace)).Msg("namespace already exists") + log.Fatal().Str("namespace", string(namespace)).Msg("namespace already exists") } obj := loadNS[*ObjectStore[Ptr]](namespace) stores[namespace] = obj diff --git a/internal/logging/accesslog/access_logger.go b/internal/logging/accesslog/access_logger.go index 8d6a83e..1568e1a 100644 --- a/internal/logging/accesslog/access_logger.go +++ b/internal/logging/accesslog/access_logger.go @@ -8,8 +8,8 @@ import ( "time" "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" maxmind "github.com/yusing/go-proxy/internal/maxmind/types" "github.com/yusing/go-proxy/internal/task" "github.com/yusing/go-proxy/internal/utils" @@ -120,7 +120,7 @@ func NewAccessLoggerWithIO(parent task.Parent, writer WriterWithName, anyCfg Any bufSize: MinBufferSize, lineBufPool: synk.NewBytesPool(), errRateLimiter: rate.NewLimiter(rate.Every(errRateLimit), errBurst), - logger: logging.With().Str("file", writer.Name()).Logger(), + logger: log.With().Str("file", writer.Name()).Logger(), } l.supportRotate = unwrap[supportRotate](writer) diff --git a/internal/logging/accesslog/file_logger.go b/internal/logging/accesslog/file_logger.go index 7a85662..8670aa0 100644 --- a/internal/logging/accesslog/file_logger.go +++ b/internal/logging/accesslog/file_logger.go @@ -7,7 +7,7 @@ import ( "path/filepath" "sync" - "github.com/yusing/go-proxy/internal/logging" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/utils" ) @@ -90,7 +90,7 @@ func (f *File) Close() error { } func (f *File) closeOnZero() { - defer logging.Debug(). + defer log.Debug(). Str("path", f.path). Msg("access log closed") diff --git a/internal/logging/logging.go b/internal/logging/logging.go index ec6a2bf..787ee27 100644 --- a/internal/logging/logging.go +++ b/internal/logging/logging.go @@ -66,21 +66,3 @@ func InitLogger(out ...io.Writer) { zerolog.TimeFieldFormat = timeFmt zerologlog.Logger = logger } - -func DiscardLogger() { zerolog.SetGlobalLevel(zerolog.Disabled) } - -func AddHook(h zerolog.Hook) { logger = logger.Hook(h) } - -func GetLogger() *zerolog.Logger { return &logger } -func With() zerolog.Context { return logger.With() } - -func WithLevel(level zerolog.Level) *zerolog.Event { return logger.WithLevel(level) } - -func Info() *zerolog.Event { return logger.Info() } -func Warn() *zerolog.Event { return logger.Warn() } -func Error() *zerolog.Event { return logger.Error() } -func Err(err error) *zerolog.Event { return logger.Err(err) } -func Debug() *zerolog.Event { return logger.Debug() } -func Fatal() *zerolog.Event { return logger.Fatal() } -func Panic() *zerolog.Event { return logger.Panic() } -func Trace() *zerolog.Event { return logger.Trace() } diff --git a/internal/maxmind/types/config.go b/internal/maxmind/types/config.go index 298f3a5..a2bb526 100644 --- a/internal/maxmind/types/config.go +++ b/internal/maxmind/types/config.go @@ -2,8 +2,8 @@ package maxmind import ( "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" ) type ( @@ -28,6 +28,6 @@ func (cfg *Config) Validate() gperr.Error { } func (cfg *Config) Logger() *zerolog.Logger { - l := logging.With().Str("database", string(cfg.Database)).Logger() + l := log.With().Str("database", string(cfg.Database)).Logger() return &l } diff --git a/internal/metrics/period/poller.go b/internal/metrics/period/poller.go index 9422f7a..46a8b11 100644 --- a/internal/metrics/period/poller.go +++ b/internal/metrics/period/poller.go @@ -10,8 +10,8 @@ import ( "sync" "time" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/task" "github.com/yusing/go-proxy/internal/utils/atomic" ) @@ -47,7 +47,7 @@ var initDataDirOnce sync.Once func initDataDir() { if err := os.MkdirAll(saveBaseDir, 0o755); err != nil { - logging.Error().Err(err).Msg("failed to create metrics data directory") + log.Error().Err(err).Msg("failed to create metrics data directory") } } @@ -138,10 +138,10 @@ func (p *Poller[T, AggregateT]) Start() { err := p.load() if err != nil { if !os.IsNotExist(err) { - logging.Error().Err(err).Msgf("failed to load last metrics data for %s", p.name) + log.Error().Err(err).Msgf("failed to load last metrics data for %s", p.name) } } else { - logging.Debug().Msgf("Loaded last metrics data for %s, %d entries", p.name, p.period.Total()) + log.Debug().Msgf("Loaded last metrics data for %s, %d entries", p.name, p.period.Total()) } go func() { @@ -158,7 +158,7 @@ func (p *Poller[T, AggregateT]) Start() { t.Finish(nil) }() - logging.Debug().Msgf("Starting poller %s with interval %s", p.name, pollInterval) + log.Debug().Msgf("Starting poller %s with interval %s", p.name, pollInterval) p.pollWithTimeout(t.Context()) @@ -176,7 +176,7 @@ func (p *Poller[T, AggregateT]) Start() { case <-gatherErrsTicker.C: errs, ok := p.gatherErrs() if ok { - logging.Error().Msg(errs) + log.Error().Msg(errs) } p.clearErrs() } diff --git a/internal/metrics/systeminfo/system_info.go b/internal/metrics/systeminfo/system_info.go index c76d165..05e317e 100644 --- a/internal/metrics/systeminfo/system_info.go +++ b/internal/metrics/systeminfo/system_info.go @@ -8,6 +8,7 @@ import ( "syscall" "time" + "github.com/rs/zerolog/log" "github.com/shirou/gopsutil/v4/cpu" "github.com/shirou/gopsutil/v4/disk" "github.com/shirou/gopsutil/v4/mem" @@ -16,7 +17,6 @@ import ( "github.com/shirou/gopsutil/v4/warning" "github.com/yusing/go-proxy/internal/common" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/metrics/period" ) @@ -130,7 +130,7 @@ func getSystemInfo(ctx context.Context, lastResult *SystemInfo) (*SystemInfo, er } }) if allWarnings.HasError() { - logging.Warn().Msg(allWarnings.String()) + log.Warn().Msg(allWarnings.String()) } if allErrors.HasError() { return nil, allErrors.Error() @@ -195,7 +195,7 @@ func (s *SystemInfo) collectDisksInfo(ctx context.Context, lastResult *SystemInf if len(s.Disks) == 0 { return errs.Error() } - logging.Warn().Msg(errs.String()) + log.Warn().Msg(errs.String()) } return nil } diff --git a/internal/net/gphttp/body.go b/internal/net/gphttp/body.go index b2d0173..be0bf51 100644 --- a/internal/net/gphttp/body.go +++ b/internal/net/gphttp/body.go @@ -6,7 +6,7 @@ import ( "errors" "net/http" - "github.com/yusing/go-proxy/internal/logging" + "github.com/rs/zerolog/log" ) func WriteBody(w http.ResponseWriter, body []byte) { @@ -14,9 +14,9 @@ func WriteBody(w http.ResponseWriter, body []byte) { switch { case errors.Is(err, http.ErrHandlerTimeout), errors.Is(err, context.DeadlineExceeded): - logging.Err(err).Msg("timeout writing body") + log.Err(err).Msg("timeout writing body") default: - logging.Err(err).Msg("failed to write body") + log.Err(err).Msg("failed to write body") } } } diff --git a/internal/net/gphttp/gpwebsocket/utils.go b/internal/net/gphttp/gpwebsocket/utils.go index 0a0d229..c5bd3cc 100644 --- a/internal/net/gphttp/gpwebsocket/utils.go +++ b/internal/net/gphttp/gpwebsocket/utils.go @@ -9,11 +9,11 @@ import ( "time" "github.com/gorilla/websocket" - "github.com/yusing/go-proxy/internal/logging" + "github.com/rs/zerolog/log" ) func warnNoMatchDomains() { - logging.Warn().Msg("no match domains configured, accepting websocket API request from all origins") + log.Warn().Msg("no match domains configured, accepting websocket API request from all origins") } var warnNoMatchDomainOnce sync.Once diff --git a/internal/net/gphttp/loadbalancer/loadbalancer.go b/internal/net/gphttp/loadbalancer/loadbalancer.go index d36bf98..90b795c 100644 --- a/internal/net/gphttp/loadbalancer/loadbalancer.go +++ b/internal/net/gphttp/loadbalancer/loadbalancer.go @@ -7,8 +7,8 @@ import ( "time" "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/net/gphttp/httpheaders" "github.com/yusing/go-proxy/internal/net/gphttp/loadbalancer/types" "github.com/yusing/go-proxy/internal/task" @@ -47,7 +47,7 @@ func New(cfg *Config) *LoadBalancer { lb := &LoadBalancer{ Config: new(Config), pool: pool.New[Server]("loadbalancer." + cfg.Link), - l: logging.With().Str("name", cfg.Link).Logger(), + l: log.With().Str("name", cfg.Link).Logger(), } lb.UpdateConfigIfNeeded(cfg) return lb diff --git a/internal/net/gphttp/logging.go b/internal/net/gphttp/logging.go index cfb67f0..492b398 100644 --- a/internal/net/gphttp/logging.go +++ b/internal/net/gphttp/logging.go @@ -4,11 +4,11 @@ import ( "net/http" "github.com/rs/zerolog" - "github.com/yusing/go-proxy/internal/logging" + "github.com/rs/zerolog/log" ) func reqLogger(r *http.Request, level zerolog.Level) *zerolog.Event { - return logging.WithLevel(level). + return log.WithLevel(level). Str("remote", r.RemoteAddr). Str("host", r.Host). Str("uri", r.Method+" "+r.RequestURI) diff --git a/internal/net/gphttp/middleware/captcha/middleware.go b/internal/net/gphttp/middleware/captcha/middleware.go index 91da59c..c4769ab 100644 --- a/internal/net/gphttp/middleware/captcha/middleware.go +++ b/internal/net/gphttp/middleware/captcha/middleware.go @@ -4,8 +4,8 @@ import ( "net/http" "text/template" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/auth" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/net/gphttp" _ "embed" @@ -55,7 +55,7 @@ func PreRequest(p Provider, w http.ResponseWriter, r *http.Request) (proceed boo "FormHTML": p.FormHTML(), }) if err != nil { - logging.Error().Err(err).Msg("failed to execute captcha page") + log.Error().Err(err).Msg("failed to execute captcha page") } return false } diff --git a/internal/net/gphttp/middleware/cloudflare_real_ip.go b/internal/net/gphttp/middleware/cloudflare_real_ip.go index 19314d6..49da655 100644 --- a/internal/net/gphttp/middleware/cloudflare_real_ip.go +++ b/internal/net/gphttp/middleware/cloudflare_real_ip.go @@ -9,8 +9,8 @@ import ( "sync" "time" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/common" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/net/types" "github.com/yusing/go-proxy/internal/utils/atomic" "github.com/yusing/go-proxy/internal/utils/strutils" @@ -89,16 +89,16 @@ func tryFetchCFCIDR() (cfCIDRs []*types.CIDR) { ) if err != nil { cfCIDRsLastUpdate.Store(time.Now().Add(-cfCIDRsUpdateRetryInterval - cfCIDRsUpdateInterval)) - logging.Err(err).Msg("failed to update cloudflare range, retry in " + strutils.FormatDuration(cfCIDRsUpdateRetryInterval)) + log.Err(err).Msg("failed to update cloudflare range, retry in " + strutils.FormatDuration(cfCIDRsUpdateRetryInterval)) return nil } if len(cfCIDRs) == 0 { - logging.Warn().Msg("cloudflare CIDR range is empty") + log.Warn().Msg("cloudflare CIDR range is empty") } } cfCIDRsLastUpdate.Store(time.Now()) - logging.Info().Msg("cloudflare CIDR range updated") + log.Info().Msg("cloudflare CIDR range updated") return } diff --git a/internal/net/gphttp/middleware/custom_error_page.go b/internal/net/gphttp/middleware/custom_error_page.go index 76110be..baef63f 100644 --- a/internal/net/gphttp/middleware/custom_error_page.go +++ b/internal/net/gphttp/middleware/custom_error_page.go @@ -8,7 +8,7 @@ import ( "strconv" "strings" - "github.com/yusing/go-proxy/internal/logging" + "github.com/rs/zerolog/log" gphttp "github.com/yusing/go-proxy/internal/net/gphttp" "github.com/yusing/go-proxy/internal/net/gphttp/httpheaders" "github.com/yusing/go-proxy/internal/net/gphttp/middleware/errorpage" @@ -32,7 +32,7 @@ func (customErrorPage) modifyResponse(resp *http.Response) error { if !gphttp.IsSuccess(resp.StatusCode) && (contentType.IsHTML() || contentType.IsPlainText()) { errorPage, ok := errorpage.GetErrorPageByStatus(resp.StatusCode) if ok { - logging.Debug().Msgf("error page for status %d loaded", resp.StatusCode) + log.Debug().Msgf("error page for status %d loaded", resp.StatusCode) _, _ = io.Copy(io.Discard, resp.Body) // drain the original body resp.Body.Close() resp.Body = io.NopCloser(bytes.NewReader(errorPage)) @@ -40,7 +40,7 @@ func (customErrorPage) modifyResponse(resp *http.Response) error { resp.Header.Set(httpheaders.HeaderContentLength, strconv.Itoa(len(errorPage))) resp.Header.Set(httpheaders.HeaderContentType, "text/html; charset=utf-8") } else { - logging.Error().Msgf("unable to load error page for status %d", resp.StatusCode) + log.Error().Msgf("unable to load error page for status %d", resp.StatusCode) } return nil } @@ -56,7 +56,7 @@ func ServeStaticErrorPageFile(w http.ResponseWriter, r *http.Request) (served bo filename := path[len(StaticFilePathPrefix):] file, ok := errorpage.GetStaticFile(filename) if !ok { - logging.Error().Msg("unable to load resource " + filename) + log.Error().Msg("unable to load resource " + filename) return false } ext := filepath.Ext(filename) @@ -68,10 +68,10 @@ func ServeStaticErrorPageFile(w http.ResponseWriter, r *http.Request) (served bo case ".css": w.Header().Set(httpheaders.HeaderContentType, "text/css; charset=utf-8") default: - logging.Error().Msgf("unexpected file type %q for %s", ext, filename) + log.Error().Msgf("unexpected file type %q for %s", ext, filename) } if _, err := w.Write(file); err != nil { - logging.Err(err).Msg("unable to write resource " + filename) + log.Err(err).Msg("unable to write resource " + filename) http.Error(w, "Error page failure", http.StatusInternalServerError) } return true diff --git a/internal/net/gphttp/middleware/errorpage/error_page.go b/internal/net/gphttp/middleware/errorpage/error_page.go index a1acec6..e63b65a 100644 --- a/internal/net/gphttp/middleware/errorpage/error_page.go +++ b/internal/net/gphttp/middleware/errorpage/error_page.go @@ -6,9 +6,9 @@ import ( "path" "sync" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/common" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/task" U "github.com/yusing/go-proxy/internal/utils" F "github.com/yusing/go-proxy/internal/utils/functional" @@ -48,7 +48,7 @@ func GetErrorPageByStatus(statusCode int) (content []byte, ok bool) { func loadContent() { files, err := U.ListFiles(errPagesBasePath, 0) if err != nil { - logging.Err(err).Msg("failed to list error page resources") + log.Err(err).Msg("failed to list error page resources") return } for _, file := range files { @@ -57,11 +57,11 @@ func loadContent() { } content, err := os.ReadFile(file) if err != nil { - logging.Warn().Err(err).Msgf("failed to read error page resource %s", file) + log.Warn().Err(err).Msgf("failed to read error page resource %s", file) continue } file = path.Base(file) - logging.Info().Msgf("error page resource %s loaded", file) + log.Info().Msgf("error page resource %s loaded", file) fileContentMap.Store(file, content) } } @@ -83,9 +83,9 @@ func watchDir() { loadContent() case events.ActionFileDeleted: fileContentMap.Delete(filename) - logging.Warn().Msgf("error page resource %s deleted", filename) + log.Warn().Msgf("error page resource %s deleted", filename) case events.ActionFileRenamed: - logging.Warn().Msgf("error page resource %s deleted", filename) + log.Warn().Msgf("error page resource %s deleted", filename) fileContentMap.Delete(filename) loadContent() } diff --git a/internal/net/gphttp/middleware/middleware.go b/internal/net/gphttp/middleware/middleware.go index bab1cb8..ab7227f 100644 --- a/internal/net/gphttp/middleware/middleware.go +++ b/internal/net/gphttp/middleware/middleware.go @@ -8,8 +8,8 @@ import ( "sort" "strings" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" gphttp "github.com/yusing/go-proxy/internal/net/gphttp" "github.com/yusing/go-proxy/internal/net/gphttp/reverseproxy" "github.com/yusing/go-proxy/internal/serialization" @@ -87,7 +87,7 @@ func NewMiddleware[ImplType any]() *Middleware { func (m *Middleware) enableTrace() { if tracer, ok := m.impl.(MiddlewareWithTracer); ok { tracer.enableTrace() - logging.Trace().Msgf("middleware %s enabled trace", m.name) + log.Trace().Msgf("middleware %s enabled trace", m.name) } } diff --git a/internal/net/gphttp/middleware/middlewares.go b/internal/net/gphttp/middleware/middlewares.go index ca2a85f..8ae4ee9 100644 --- a/internal/net/gphttp/middleware/middlewares.go +++ b/internal/net/gphttp/middleware/middlewares.go @@ -3,9 +3,9 @@ package middleware import ( "path" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/common" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/utils" "github.com/yusing/go-proxy/internal/utils/strutils" ) @@ -59,7 +59,7 @@ func LoadComposeFiles() { errs := gperr.NewBuilder("middleware compile errors") middlewareDefs, err := utils.ListFiles(common.MiddlewareComposeBasePath, 0) if err != nil { - logging.Err(err).Msg("failed to list middleware definitions") + log.Err(err).Msg("failed to list middleware definitions") return } for _, defFile := range middlewareDefs { @@ -75,7 +75,7 @@ func LoadComposeFiles() { continue } allMiddlewares[name] = m - logging.Info(). + log.Info(). Str("src", path.Base(defFile)). Str("name", name). Msg("middleware loaded") @@ -94,7 +94,7 @@ func LoadComposeFiles() { continue } allMiddlewares[name] = m - logging.Info(). + log.Info(). Str("src", path.Base(defFile)). Str("name", name). Msg("middleware loaded") diff --git a/internal/net/gphttp/reverseproxy/reverse_proxy.go b/internal/net/gphttp/reverseproxy/reverse_proxy.go index a28d871..886a434 100644 --- a/internal/net/gphttp/reverseproxy/reverse_proxy.go +++ b/internal/net/gphttp/reverseproxy/reverse_proxy.go @@ -25,7 +25,7 @@ import ( "sync" "github.com/rs/zerolog" - "github.com/yusing/go-proxy/internal/logging" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/logging/accesslog" "github.com/yusing/go-proxy/internal/net/gphttp/httpheaders" "github.com/yusing/go-proxy/internal/net/types" @@ -138,7 +138,7 @@ func NewReverseProxy(name string, target *types.URL, transport http.RoundTripper panic("nil transport") } rp := &ReverseProxy{ - Logger: logging.With().Str("name", name).Logger(), + Logger: log.With().Str("name", name).Logger(), Transport: transport, TargetName: name, TargetURL: target, @@ -173,17 +173,17 @@ func (p *ReverseProxy) errorHandler(rw http.ResponseWriter, r *http.Request, err case errors.Is(err, context.Canceled), errors.Is(err, io.EOF), errors.Is(err, context.DeadlineExceeded): - logging.Debug().Err(err).Str("url", reqURL).Msg("http proxy error") + log.Debug().Err(err).Str("url", reqURL).Msg("http proxy error") default: var recordErr tls.RecordHeaderError if errors.As(err, &recordErr) { - logging.Error(). + log.Error(). Str("url", reqURL). Msgf(`scheme was likely misconfigured as https, try setting "proxy.%s.scheme" back to "http"`, p.TargetName) - logging.Err(err).Msg("underlying error") + log.Err(err).Msg("underlying error") } else { - logging.Err(err).Str("url", reqURL).Msg("http proxy error") + log.Err(err).Str("url", reqURL).Msg("http proxy error") } } diff --git a/internal/net/gphttp/server/server.go b/internal/net/gphttp/server/server.go index c42afec..d7e71b5 100644 --- a/internal/net/gphttp/server/server.go +++ b/internal/net/gphttp/server/server.go @@ -9,9 +9,9 @@ import ( "github.com/quic-go/quic-go/http3" "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/acl" "github.com/yusing/go-proxy/internal/common" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/task" ) @@ -53,7 +53,7 @@ func StartServer(parent task.Parent, opt Options) (s *Server) { func NewServer(opt Options) (s *Server) { var httpSer, httpsSer *http.Server - logger := logging.With().Str("server", opt.Name).Logger() + logger := log.With().Str("server", opt.Name).Logger() certAvailable := false if opt.CertProvider != nil { diff --git a/internal/notif/providers.go b/internal/notif/providers.go index 4327242..be7ba9f 100644 --- a/internal/notif/providers.go +++ b/internal/notif/providers.go @@ -8,8 +8,8 @@ import ( "net/http" "time" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/serialization" ) @@ -73,7 +73,7 @@ func (msg *LogMessage) notify(ctx context.Context, provider Provider) error { switch resp.StatusCode { case http.StatusOK, http.StatusCreated, http.StatusAccepted, http.StatusNoContent: body, _ := io.ReadAll(resp.Body) - logging.Debug(). + log.Debug(). Str("provider", provider.GetName()). Str("url", provider.GetURL()). Str("status", resp.Status). diff --git a/internal/route/provider/docker.go b/internal/route/provider/docker.go index 111018d..cbe6410 100755 --- a/internal/route/provider/docker.go +++ b/internal/route/provider/docker.go @@ -7,10 +7,10 @@ import ( "github.com/docker/docker/client" "github.com/goccy/go-yaml" "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/common" "github.com/yusing/go-proxy/internal/docker" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/route" "github.com/yusing/go-proxy/internal/serialization" "github.com/yusing/go-proxy/internal/utils/strutils" @@ -36,7 +36,7 @@ func DockerProviderImpl(name, dockerHost string) ProviderImpl { return &DockerProvider{ name, dockerHost, - logging.With().Str("type", "docker").Str("name", name).Logger(), + log.With().Str("type", "docker").Str("name", name).Logger(), } } diff --git a/internal/route/provider/file.go b/internal/route/provider/file.go index 6d964cc..06921b7 100644 --- a/internal/route/provider/file.go +++ b/internal/route/provider/file.go @@ -6,9 +6,9 @@ import ( "strings" "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/common" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/route" "github.com/yusing/go-proxy/internal/serialization" W "github.com/yusing/go-proxy/internal/watcher" @@ -24,7 +24,7 @@ func FileProviderImpl(filename string) (ProviderImpl, error) { impl := &FileProvider{ fileName: filename, path: path.Join(common.ConfigBasePath, filename), - l: logging.With().Str("type", "file").Str("name", filename).Logger(), + l: log.With().Str("type", "file").Str("name", filename).Logger(), } _, err := os.Stat(impl.path) if err != nil { diff --git a/internal/route/route.go b/internal/route/route.go index 9ff3eb6..62c41f5 100644 --- a/internal/route/route.go +++ b/internal/route/route.go @@ -7,12 +7,12 @@ import ( "time" "github.com/docker/docker/api/types/container" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/agent/pkg/agent" "github.com/yusing/go-proxy/internal/docker" "github.com/yusing/go-proxy/internal/gperr" "github.com/yusing/go-proxy/internal/homepage" idlewatcher "github.com/yusing/go-proxy/internal/idlewatcher/types" - "github.com/yusing/go-proxy/internal/logging" netutils "github.com/yusing/go-proxy/internal/net" net "github.com/yusing/go-proxy/internal/net/types" "github.com/yusing/go-proxy/internal/proxmox" @@ -116,7 +116,7 @@ func (r *Route) Validate() gperr.Error { Subject(containerName) } - l := logging.With().Str("container", containerName).Logger() + l := log.With().Str("container", containerName).Logger() l.Info().Msg("checking if container is running") running, err := node.LXCIsRunning(ctx, vmid) diff --git a/internal/route/stream.go b/internal/route/stream.go index bd87cfe..9c76de0 100755 --- a/internal/route/stream.go +++ b/internal/route/stream.go @@ -5,9 +5,9 @@ import ( "errors" "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/gperr" "github.com/yusing/go-proxy/internal/idlewatcher" - "github.com/yusing/go-proxy/internal/logging" net "github.com/yusing/go-proxy/internal/net/types" "github.com/yusing/go-proxy/internal/route/routes" "github.com/yusing/go-proxy/internal/task" @@ -32,7 +32,7 @@ func NewStreamRoute(base *Route) (routes.Route, gperr.Error) { // TODO: support non-coherent scheme return &StreamRoute{ Route: base, - l: logging.With(). + l: log.With(). Str("type", string(base.Scheme)). Str("name", base.Name()). Logger(), diff --git a/internal/route/udp_forwarder.go b/internal/route/udp_forwarder.go index 62149af..581e273 100644 --- a/internal/route/udp_forwarder.go +++ b/internal/route/udp_forwarder.go @@ -6,8 +6,8 @@ import ( "net" "sync" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/net/types" F "github.com/yusing/go-proxy/internal/utils/functional" ) @@ -88,7 +88,7 @@ func (w *UDPForwarder) dialDst() (dstConn net.Conn, err error) { func (w *UDPForwarder) readFromListener(buf *UDPBuf) (srcAddr *net.UDPAddr, err error) { buf.n, buf.oobn, _, srcAddr, err = w.forwarder.ReadMsgUDP(buf.data, buf.oob) if err == nil { - logging.Debug().Msgf("read from listener udp://%s success (n: %d, oobn: %d)", w.Addr().String(), buf.n, buf.oobn) + log.Debug().Msgf("read from listener udp://%s success (n: %d, oobn: %d)", w.Addr().String(), buf.n, buf.oobn) } return } @@ -102,7 +102,7 @@ func (conn *UDPConn) read() (err error) { conn.buf.oobn = 0 } if err == nil { - logging.Debug().Msgf("read from dst %s success (n: %d, oobn: %d)", conn.DstAddrString(), conn.buf.n, conn.buf.oobn) + log.Debug().Msgf("read from dst %s success (n: %d, oobn: %d)", conn.DstAddrString(), conn.buf.n, conn.buf.oobn) } return } @@ -110,7 +110,7 @@ func (conn *UDPConn) read() (err error) { func (w *UDPForwarder) writeToSrc(srcAddr *net.UDPAddr, buf *UDPBuf) (err error) { buf.n, buf.oobn, err = w.forwarder.WriteMsgUDP(buf.data[:buf.n], buf.oob[:buf.oobn], srcAddr) if err == nil { - logging.Debug().Msgf("write to src %s://%s success (n: %d, oobn: %d)", srcAddr.Network(), srcAddr.String(), buf.n, buf.oobn) + log.Debug().Msgf("write to src %s://%s success (n: %d, oobn: %d)", srcAddr.Network(), srcAddr.String(), buf.n, buf.oobn) } return } @@ -120,12 +120,12 @@ func (conn *UDPConn) write() (err error) { case *net.UDPConn: conn.buf.n, conn.buf.oobn, err = dstConn.WriteMsgUDP(conn.buf.data[:conn.buf.n], conn.buf.oob[:conn.buf.oobn], nil) if err == nil { - logging.Debug().Msgf("write to dst %s success (n: %d, oobn: %d)", conn.DstAddrString(), conn.buf.n, conn.buf.oobn) + log.Debug().Msgf("write to dst %s success (n: %d, oobn: %d)", conn.DstAddrString(), conn.buf.n, conn.buf.oobn) } default: _, err = dstConn.Write(conn.buf.data[:conn.buf.n]) if err == nil { - logging.Debug().Msgf("write to dst %s success (n: %d)", conn.DstAddrString(), conn.buf.n) + log.Debug().Msgf("write to dst %s success (n: %d)", conn.DstAddrString(), conn.buf.n) } } diff --git a/internal/task/task.go b/internal/task/task.go index 2421a13..9faa7a6 100644 --- a/internal/task/task.go +++ b/internal/task/task.go @@ -7,9 +7,9 @@ import ( "sync/atomic" "time" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/common" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/utils/strutils" ) @@ -116,14 +116,14 @@ func (t *Task) Finish(reason any) { func (t *Task) finish(reason any) { t.cancel(fmtCause(reason)) if !waitWithTimeout(t.childrenDone) { - logging.Debug(). + log.Debug(). Str("task", t.name). Strs("subtasks", t.listChildren()). Msg("Timeout waiting for subtasks to finish") } go t.runCallbacks() if !waitWithTimeout(t.callbacksDone) { - logging.Debug(). + log.Debug(). Str("task", t.name). Strs("callbacks", t.listCallbacks()). Msg("Timeout waiting for callbacks to finish") @@ -134,7 +134,7 @@ func (t *Task) finish(reason any) { } t.parent.subChildCount() allTasks.Remove(t) - logging.Trace().Msg("task " + t.name + " finished") + log.Trace().Msg("task " + t.name + " finished") } // Subtask returns a new subtask with the given name, derived from the parent's context. @@ -166,7 +166,7 @@ func (t *Task) Subtask(name string, needFinish ...bool) *Task { }() } - logging.Trace().Msg("task " + child.name + " started") + log.Trace().Msg("task " + child.name + " started") return child } @@ -189,7 +189,7 @@ func (t *Task) MarshalText() ([]byte, error) { func (t *Task) invokeWithRecover(fn func(), caller string) { defer func() { if err := recover(); err != nil { - logging.Error(). + log.Error(). Interface("err", err). Msg("panic in task " + t.name + "." + caller) if common.IsDebug { diff --git a/internal/task/utils.go b/internal/task/utils.go index da0bc36..e75b3be 100644 --- a/internal/task/utils.go +++ b/internal/task/utils.go @@ -9,7 +9,7 @@ import ( "syscall" "time" - "github.com/yusing/go-proxy/internal/logging" + "github.com/rs/zerolog/log" F "github.com/yusing/go-proxy/internal/utils/functional" ) @@ -68,10 +68,10 @@ func GracefulShutdown(timeout time.Duration) (err error) { case <-after: b, err := json.Marshal(DebugTaskList()) if err != nil { - logging.Warn().Err(err).Msg("failed to marshal tasks") + log.Warn().Err(err).Msg("failed to marshal tasks") return context.DeadlineExceeded } - logging.Warn().RawJSON("tasks", b).Msgf("Timeout waiting for these %d tasks to finish", allTasks.Size()) + log.Warn().RawJSON("tasks", b).Msgf("Timeout waiting for these %d tasks to finish", allTasks.Size()) return context.DeadlineExceeded } } @@ -87,6 +87,6 @@ func WaitExit(shutdownTimeout int) { <-sig // gracefully shutdown - logging.Info().Msg("shutting down") + log.Info().Msg("shutting down") _ = GracefulShutdown(time.Second * time.Duration(shutdownTimeout)) } diff --git a/internal/watcher/directory_watcher.go b/internal/watcher/directory_watcher.go index 45cca6a..4bfee33 100644 --- a/internal/watcher/directory_watcher.go +++ b/internal/watcher/directory_watcher.go @@ -8,8 +8,8 @@ import ( "github.com/fsnotify/fsnotify" "github.com/rs/zerolog" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/task" "github.com/yusing/go-proxy/internal/watcher/events" ) @@ -41,13 +41,13 @@ func NewDirectoryWatcher(parent task.Parent, dirPath string) *DirWatcher { //! subdirectories are not watched w, err := fsnotify.NewWatcher() if err != nil { - logging.Panic().Err(err).Msg("unable to create fs watcher") + log.Panic().Err(err).Msg("unable to create fs watcher") } if err = w.Add(dirPath); err != nil { - logging.Panic().Err(err).Msg("unable to create fs watcher") + log.Panic().Err(err).Msg("unable to create fs watcher") } helper := &DirWatcher{ - Logger: logging.With(). + Logger: log.With(). Str("type", "dir"). Str("path", dirPath). Logger(), diff --git a/internal/watcher/docker_watcher.go b/internal/watcher/docker_watcher.go index 09713c6..1a01f9e 100644 --- a/internal/watcher/docker_watcher.go +++ b/internal/watcher/docker_watcher.go @@ -8,9 +8,9 @@ import ( docker_events "github.com/docker/docker/api/types/events" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/client" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/docker" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/watcher/events" ) @@ -81,7 +81,7 @@ func (w DockerWatcher) EventsWithOptions(ctx context.Context, options DockerList }() cEventCh, cErrCh := client.Events(ctx, options) - defer logging.Debug().Str("host", client.Address()).Msg("docker watcher closed") + defer log.Debug().Str("host", client.Address()).Msg("docker watcher closed") for { select { case <-ctx.Done(): @@ -153,7 +153,7 @@ func checkConnection(ctx context.Context, client *docker.SharedClient) bool { defer cancel() err := client.CheckConnection(ctx) if err != nil { - logging.Debug().Err(err).Msg("docker watcher: connection failed") + log.Debug().Err(err).Msg("docker watcher: connection failed") return false } return true diff --git a/internal/watcher/health/monitor/monitor.go b/internal/watcher/health/monitor/monitor.go index a6b029f..9e0ead7 100644 --- a/internal/watcher/health/monitor/monitor.go +++ b/internal/watcher/health/monitor/monitor.go @@ -7,9 +7,9 @@ import ( "net/url" "time" + "github.com/rs/zerolog/log" "github.com/yusing/go-proxy/internal/docker" "github.com/yusing/go-proxy/internal/gperr" - "github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/notif" "github.com/yusing/go-proxy/internal/route/routes" "github.com/yusing/go-proxy/internal/task" @@ -48,7 +48,7 @@ func NewMonitor(r routes.Route) health.HealthMonCheck { case routes.StreamRoute: mon = NewRawHealthMonitor(&r.TargetURL().URL, r.HealthCheckConfig()) default: - logging.Panic().Msgf("unexpected route type: %T", r) + log.Panic().Msgf("unexpected route type: %T", r) } } if r.IsDocker() { @@ -91,7 +91,7 @@ func (mon *monitor) Start(parent task.Parent) gperr.Error { mon.task = parent.Subtask("health_monitor", true) go func() { - logger := logging.With().Str("name", mon.service).Logger() + logger := log.With().Str("name", mon.service).Logger() defer func() { if mon.status.Load() != health.StatusError { @@ -221,7 +221,7 @@ func (mon *monitor) MarshalJSON() ([]byte, error) { } func (mon *monitor) checkUpdateHealth() error { - logger := logging.With().Str("name", mon.Name()).Logger() + logger := log.With().Str("name", mon.Name()).Logger() result, err := mon.checkHealth() var lastStatus health.Status diff --git a/pkg/version.go b/pkg/version.go index 03c42ec..3c5ea98 100644 --- a/pkg/version.go +++ b/pkg/version.go @@ -34,16 +34,16 @@ func init() { // lastVersion = ParseVersion(lastVersionStr) // } // if err != nil && !os.IsNotExist(err) { - // logging.Warn().Err(err).Msg("failed to read version file") + // log.Warn().Err(err).Msg("failed to read version file") // return // } // if err := f.Truncate(0); err != nil { - // logging.Warn().Err(err).Msg("failed to truncate version file") + // log.Warn().Err(err).Msg("failed to truncate version file") // return // } // _, err = f.WriteString(version) // if err != nil { - // logging.Warn().Err(err).Msg("failed to save version file") + // log.Warn().Err(err).Msg("failed to save version file") // return // } }