diff --git a/.semgrep/adapter/package-import.go b/.semgrep/adapter/package-import.go index a34ce8789cd..faa858f7436 100644 --- a/.semgrep/adapter/package-import.go +++ b/.semgrep/adapter/package-import.go @@ -6,7 +6,7 @@ import ( // ruleid: package-import-check "github.com/mitchellh/copystructure" // ruleid: package-import-check - "github.com/golang/glog" + "github.com/prebid/prebid-server/v3/di" ) import ( @@ -17,7 +17,7 @@ import ( // ok: package-import-check "os" // ruleid: package-import-check - log "github.com/golang/glog" + log "github.com/prebid/prebid-server/v3/di" ) import ( @@ -32,13 +32,13 @@ import ( ) // ruleid: package-import-check -import "github.com/golang/glog" +import "github.com/prebid/prebid-server/v3/di" // ruleid: package-import-check import "github.com/mitchellh/copystructure" // ruleid: package-import-check -import log "github.com/golang/glog" +import log "github.com/prebid/prebid-server/v3/di" // ruleid: package-import-check import copy "github.com/mitchellh/copystructure" diff --git a/README.md b/README.md index b616594a68a..de604956641 100644 --- a/README.md +++ b/README.md @@ -92,6 +92,10 @@ An option for developing Prebid Server in a reproducible environment isolated fr Prebid Server is not currently intended to be imported by other projects. Go Modules is used to manage dependencies, which also makes it possible to import Prebid Server packages. This is not supported. We offer no guarantees regarding the stability of packages and do not adhere to semantic versioning guidelines. +## Swapping Global Dependencies + +Logger is a global side-effectful dependency that sometimes needs to be swapped in order to modify the behavior. This can be done compile-time in the `di` package. It contains the `interface` sub-package with a ILogger interface definition and `provider` with the implementation of the default logger (`providers/log/default.go`) and an example of an alternative (`providers/log/alternative.go`) logger. Notice that the alternative logger is compiled only if a `custom_logger` build tag is specified while default logger will not be compiled in that case. You can replace the `alternative.go` with your logger implementation, but please adhere to the interface and expose a `ProvideLogger()` function that is called by `di/di.go` to set your dependency to be used globally. This is not a dependency injection per se, but this mechanism can be extended to other similar side-effectful global dependencies besides logger. + ## Contributing > [!IMPORTANT] > All contributions must follow the [Prebid Code of Conduct](https://prebid.org/code-of-conduct/) and the [Prebid Module Rules](https://docs.prebid.org/dev-docs/module-rules.html). diff --git a/analytics/agma/agma_module.go b/analytics/agma/agma_module.go index 6ee16e93b84..79968ce43e9 100644 --- a/analytics/agma/agma_module.go +++ b/analytics/agma/agma_module.go @@ -12,10 +12,10 @@ import ( "github.com/benbjohnson/clock" "github.com/docker/go-units" - "github.com/golang/glog" "github.com/prebid/go-gdpr/vendorconsent" "github.com/prebid/prebid-server/v3/analytics" "github.com/prebid/prebid-server/v3/config" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/openrtb_ext" ) @@ -93,7 +93,7 @@ func (l *AgmaLogger) start() { for { select { case <-l.sigTermCh: - glog.Infof("[AgmaAnalytics] Received Close, trying to flush buffer") + di.Log.Infof("[AgmaAnalytics] Received Close, trying to flush buffer") l.flush() return case event := <-l.bufferCh: @@ -139,7 +139,7 @@ func (l *AgmaLogger) flush() { if err != nil { l.reset() l.mux.Unlock() - glog.Warning("[AgmaAnalytics] fail to copy the buffer") + di.Log.Warning("[AgmaAnalytics] fail to copy the buffer") return } @@ -223,7 +223,7 @@ func (l *AgmaLogger) LogAuctionObject(event *analytics.AuctionObject) { } data, err := serializeAnayltics(event.RequestWrapper, EventTypeAuction, code, event.StartTime) if err != nil { - glog.Errorf("[AgmaAnalytics] Error serializing auction object: %v", err) + di.Log.Errorf("[AgmaAnalytics] Error serializing auction object: %v", err) return } l.bufferCh <- data @@ -239,7 +239,7 @@ func (l *AgmaLogger) LogAmpObject(event *analytics.AmpObject) { } data, err := serializeAnayltics(event.RequestWrapper, EventTypeAmp, code, event.StartTime) if err != nil { - glog.Errorf("[AgmaAnalytics] Error serializing amp object: %v", err) + di.Log.Errorf("[AgmaAnalytics] Error serializing amp object: %v", err) return } l.bufferCh <- data @@ -255,14 +255,14 @@ func (l *AgmaLogger) LogVideoObject(event *analytics.VideoObject) { } data, err := serializeAnayltics(event.RequestWrapper, EventTypeVideo, code, event.StartTime) if err != nil { - glog.Errorf("[AgmaAnalytics] Error serializing video object: %v", err) + di.Log.Errorf("[AgmaAnalytics] Error serializing video object: %v", err) return } l.bufferCh <- data } func (l *AgmaLogger) Shutdown() { - glog.Info("[AgmaAnalytics] Shutdown, trying to flush buffer") + di.Log.Info("[AgmaAnalytics] Shutdown, trying to flush buffer") l.flush() // mutex safe } diff --git a/analytics/agma/sender.go b/analytics/agma/sender.go index b47b059536e..b38efd2921d 100644 --- a/analytics/agma/sender.go +++ b/analytics/agma/sender.go @@ -9,8 +9,8 @@ import ( "net/url" "time" - "github.com/golang/glog" "github.com/prebid/prebid-server/v3/config" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/version" ) @@ -50,7 +50,7 @@ func createHttpSender(httpClient *http.Client, endpoint config.AgmaAnalyticsHttp if endpoint.Gzip { requestBody, err = compressToGZIP(payload) if err != nil { - glog.Errorf("[agmaAnalytics] Compressing request failed %v", err) + di.Log.Errorf("[agmaAnalytics] Compressing request failed %v", err) return err } } else { @@ -59,7 +59,7 @@ func createHttpSender(httpClient *http.Client, endpoint config.AgmaAnalyticsHttp req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint.Url, bytes.NewBuffer(requestBody)) if err != nil { - glog.Errorf("[agmaAnalytics] Creating request failed %v", err) + di.Log.Errorf("[agmaAnalytics] Creating request failed %v", err) return err } @@ -71,12 +71,12 @@ func createHttpSender(httpClient *http.Client, endpoint config.AgmaAnalyticsHttp resp, err := httpClient.Do(req) if err != nil { - glog.Errorf("[agmaAnalytics] Sending request failed %v", err) + di.Log.Errorf("[agmaAnalytics] Sending request failed %v", err) return err } if resp.StatusCode != http.StatusOK { - glog.Errorf("[agmaAnalytics] Wrong code received %d instead of %d", resp.StatusCode, http.StatusOK) + di.Log.Errorf("[agmaAnalytics] Wrong code received %d instead of %d", resp.StatusCode, http.StatusOK) return fmt.Errorf("wrong code received %d instead of %d", resp.StatusCode, http.StatusOK) } return nil diff --git a/analytics/build/build.go b/analytics/build/build.go index 26edaa4f53b..f73216e2295 100644 --- a/analytics/build/build.go +++ b/analytics/build/build.go @@ -4,13 +4,13 @@ import ( "encoding/json" "github.com/benbjohnson/clock" - "github.com/golang/glog" "github.com/prebid/prebid-server/v3/analytics" "github.com/prebid/prebid-server/v3/analytics/agma" "github.com/prebid/prebid-server/v3/analytics/clients" "github.com/prebid/prebid-server/v3/analytics/filesystem" "github.com/prebid/prebid-server/v3/analytics/pubstack" "github.com/prebid/prebid-server/v3/config" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/openrtb_ext" "github.com/prebid/prebid-server/v3/ortb" "github.com/prebid/prebid-server/v3/privacy" @@ -23,7 +23,7 @@ func New(analytics *config.Analytics) analytics.Runner { if mod, err := filesystem.NewFileLogger(analytics.File.Filename); err == nil { modules["filelogger"] = mod } else { - glog.Fatalf("Could not initialize FileLogger for file %v :%v", analytics.File.Filename, err) + di.Log.Fatalf("Could not initialize FileLogger for file %v :%v", analytics.File.Filename, err) } } @@ -40,7 +40,7 @@ func New(analytics *config.Analytics) analytics.Runner { if err == nil { modules["pubstack"] = pubstackModule } else { - glog.Errorf("Could not initialize PubstackModule: %v", err) + di.Log.Errorf("Could not initialize PubstackModule: %v", err) } } @@ -52,7 +52,7 @@ func New(analytics *config.Analytics) analytics.Runner { if err == nil { modules["agma"] = agmaModule } else { - glog.Errorf("Could not initialize Agma Anayltics: %v", err) + di.Log.Errorf("Could not initialize Agma Anayltics: %v", err) } } diff --git a/analytics/filesystem/file_module.go b/analytics/filesystem/file_module.go index 5555752e461..da6eae79c45 100644 --- a/analytics/filesystem/file_module.go +++ b/analytics/filesystem/file_module.go @@ -3,9 +3,9 @@ package filesystem import ( "bytes" "fmt" + "github.com/prebid/prebid-server/v3/di" cglog "github.com/chasex/glog" - "github.com/golang/glog" "github.com/prebid/openrtb/v20/openrtb2" "github.com/prebid/prebid-server/v3/analytics" "github.com/prebid/prebid-server/v3/util/jsonutil" @@ -94,7 +94,7 @@ func (f *FileLogger) LogNotificationEventObject(ne *analytics.NotificationEvent) // Shutdown the logger func (f *FileLogger) Shutdown() { // clear all pending buffered data in case there is any - glog.Info("[FileLogger] Shutdown, trying to flush buffer") + di.Log.Info("[FileLogger] Shutdown, trying to flush buffer") f.Logger.Flush() } diff --git a/analytics/pubstack/eventchannel/eventchannel.go b/analytics/pubstack/eventchannel/eventchannel.go index 022cc5bcf1b..a1cc391f8c2 100644 --- a/analytics/pubstack/eventchannel/eventchannel.go +++ b/analytics/pubstack/eventchannel/eventchannel.go @@ -7,7 +7,7 @@ import ( "time" "github.com/benbjohnson/clock" - "github.com/golang/glog" + "github.com/prebid/prebid-server/v3/di" ) type Metrics struct { @@ -66,7 +66,7 @@ func (c *EventChannel) buffer(event []byte) { _, err := c.gz.Write(event) if err != nil { - glog.Warning("[pubstack] fail to compress, skip the event") + di.Log.Warning("[pubstack] fail to compress, skip the event") return } @@ -104,7 +104,7 @@ func (c *EventChannel) flush() { // finish writing gzip header err := c.gz.Close() if err != nil { - glog.Warning("[pubstack] fail to close gzipped buffer") + di.Log.Warning("[pubstack] fail to close gzipped buffer") return } @@ -112,7 +112,7 @@ func (c *EventChannel) flush() { payload := make([]byte, c.buff.Len()) _, err = c.buff.Read(payload) if err != nil { - glog.Warning("[pubstack] fail to copy the buffer") + di.Log.Warning("[pubstack] fail to copy the buffer") return } diff --git a/analytics/pubstack/eventchannel/sender.go b/analytics/pubstack/eventchannel/sender.go index fe068b1555f..e645f24f474 100644 --- a/analytics/pubstack/eventchannel/sender.go +++ b/analytics/pubstack/eventchannel/sender.go @@ -7,7 +7,7 @@ import ( "net/url" "path" - "github.com/golang/glog" + "github.com/prebid/prebid-server/v3/di" ) type Sender = func(payload []byte) error @@ -16,7 +16,7 @@ func NewHttpSender(client *http.Client, endpoint string) Sender { return func(payload []byte) error { req, err := http.NewRequest(http.MethodPost, endpoint, bytes.NewReader(payload)) if err != nil { - glog.Error(err) + di.Log.Error(err) return err } @@ -30,7 +30,7 @@ func NewHttpSender(client *http.Client, endpoint string) Sender { resp.Body.Close() if resp.StatusCode != http.StatusOK { - glog.Errorf("[pubstack] Wrong code received %d instead of %d", resp.StatusCode, http.StatusOK) + di.Log.Errorf("[pubstack] Wrong code received %d instead of %d", resp.StatusCode, http.StatusOK) return fmt.Errorf("wrong code received %d instead of %d", resp.StatusCode, http.StatusOK) } return nil @@ -40,7 +40,7 @@ func NewHttpSender(client *http.Client, endpoint string) Sender { func BuildEndpointSender(client *http.Client, baseUrl string, module string) Sender { endpoint, err := url.Parse(baseUrl) if err != nil { - glog.Error(err) + di.Log.Error(err) } endpoint.Path = path.Join(endpoint.Path, "intake", module) return NewHttpSender(client, endpoint.String()) diff --git a/analytics/pubstack/pubstack_module.go b/analytics/pubstack/pubstack_module.go index c5bb02e2eb7..58f05fa95ba 100644 --- a/analytics/pubstack/pubstack_module.go +++ b/analytics/pubstack/pubstack_module.go @@ -10,7 +10,7 @@ import ( "time" "github.com/benbjohnson/clock" - "github.com/golang/glog" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/analytics" "github.com/prebid/prebid-server/v3/analytics/pubstack/eventchannel" @@ -64,7 +64,7 @@ func NewModule(client *http.Client, scope, endpoint, configRefreshDelay string, } func NewModuleWithConfigTask(client *http.Client, scope, endpoint string, maxEventCount int, maxByteSize, maxTime string, configTask ConfigUpdateTask, clock clock.Clock) (analytics.Module, error) { - glog.Infof("[pubstack] Initializing module scope=%s endpoint=%s\n", scope, endpoint) + di.Log.Infof("[pubstack] Initializing module scope=%s endpoint=%s\n", scope, endpoint) // parse args bufferCfg, err := newBufferConfig(maxEventCount, maxByteSize, maxTime) @@ -103,7 +103,7 @@ func NewModuleWithConfigTask(client *http.Client, scope, endpoint string, maxEve configChannel := configTask.Start(pb.stopCh) go pb.start(configChannel) - glog.Info("[pubstack] Pubstack analytics configured and ready") + di.Log.Info("[pubstack] Pubstack analytics configured and ready") return &pb, nil } @@ -118,7 +118,7 @@ func (p *PubstackModule) LogAuctionObject(ao *analytics.AuctionObject) { // serialize event payload, err := helpers.JsonifyAuctionObject(ao, p.scope) if err != nil { - glog.Warning("[pubstack] Cannot serialize auction") + di.Log.Warning("[pubstack] Cannot serialize auction") return } @@ -139,7 +139,7 @@ func (p *PubstackModule) LogVideoObject(vo *analytics.VideoObject) { // serialize event payload, err := helpers.JsonifyVideoObject(vo, p.scope) if err != nil { - glog.Warning("[pubstack] Cannot serialize video") + di.Log.Warning("[pubstack] Cannot serialize video") return } @@ -157,7 +157,7 @@ func (p *PubstackModule) LogSetUIDObject(so *analytics.SetUIDObject) { // serialize event payload, err := helpers.JsonifySetUIDObject(so, p.scope) if err != nil { - glog.Warning("[pubstack] Cannot serialize video") + di.Log.Warning("[pubstack] Cannot serialize video") return } @@ -175,7 +175,7 @@ func (p *PubstackModule) LogCookieSyncObject(cso *analytics.CookieSyncObject) { // serialize event payload, err := helpers.JsonifyCookieSync(cso, p.scope) if err != nil { - glog.Warning("[pubstack] Cannot serialize video") + di.Log.Warning("[pubstack] Cannot serialize video") return } @@ -193,7 +193,7 @@ func (p *PubstackModule) LogAmpObject(ao *analytics.AmpObject) { // serialize event payload, err := helpers.JsonifyAmpObject(ao, p.scope) if err != nil { - glog.Warning("[pubstack] Cannot serialize video") + di.Log.Warning("[pubstack] Cannot serialize video") return } @@ -203,7 +203,7 @@ func (p *PubstackModule) LogAmpObject(ao *analytics.AmpObject) { // Shutdown - no op since the analytic module already implements system signal handling // and trying to close a closed channel will cause panic func (p *PubstackModule) Shutdown() { - glog.Info("[PubstackModule] Shutdown") + di.Log.Info("[PubstackModule] Shutdown") } func (p *PubstackModule) start(c <-chan *Configuration) { @@ -216,7 +216,7 @@ func (p *PubstackModule) start(c <-chan *Configuration) { return case config := <-c: p.updateConfig(config) - glog.Infof("[pubstack] Updating config: %v", p.cfg) + di.Log.Infof("[pubstack] Updating config: %v", p.cfg) } } } diff --git a/config/config.go b/config/config.go index 30f8d69adc1..e09f401a7d5 100644 --- a/config/config.go +++ b/config/config.go @@ -9,9 +9,9 @@ import ( "strings" "time" - "github.com/golang/glog" "github.com/prebid/go-gdpr/consentconstants" "github.com/prebid/openrtb/v20/openrtb2" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/errortypes" "github.com/prebid/prebid-server/v3/openrtb_ext" "github.com/prebid/prebid-server/v3/util/jsonutil" @@ -151,11 +151,11 @@ func (cfg *Configuration) validate(v *viper.Viper) []error { errs = cfg.ExtCacheURL.validate(errs) errs = cfg.AccountDefaults.PriceFloors.validate(errs) if cfg.AccountDefaults.Disabled { - glog.Warning(`With account_defaults.disabled=true, host-defined accounts must exist and have "disabled":false. All other requests will be rejected.`) + di.Log.Warning(`With account_defaults.disabled=true, host-defined accounts must exist and have "disabled":false. All other requests will be rejected.`) } if cfg.AccountDefaults.Events.Enabled { - glog.Warning(`account_defaults.events has no effect as the feature is under development.`) + di.Log.Warning(`account_defaults.events has no effect as the feature is under development.`) } errs = cfg.Experiment.validate(errs) @@ -267,7 +267,7 @@ func (cfg *GDPR) validate(v *viper.Viper, errs []error) []error { errs = append(errs, fmt.Errorf("gdpr.host_vendor_id must be in the range [0, %d]. Got %d", 0xffff, cfg.HostVendorID)) } if cfg.HostVendorID == 0 { - glog.Warning("gdpr.host_vendor_id was not specified. Host company GDPR checks will be skipped.") + di.Log.Warning("gdpr.host_vendor_id was not specified. Host company GDPR checks will be skipped.") } if cfg.AMPException { errs = append(errs, fmt.Errorf("gdpr.amp_exception has been discontinued and must be removed from your config. If you need to disable GDPR for AMP, you may do so per-account (gdpr.integration_enabled.amp) or at the host level for the default account (account_defaults.gdpr.integration_enabled.amp)")) @@ -725,7 +725,7 @@ func New(v *viper.Viper, bidderInfos BidderInfos, normalizeBidderName openrtb_ex } if err := isValidCookieSize(c.HostCookie.MaxCookieSizeBytes); err != nil { - glog.Fatal(fmt.Printf("Max cookie size %d cannot be less than %d \n", c.HostCookie.MaxCookieSizeBytes, MIN_COOKIE_SIZE_BYTES)) + di.Log.Fatal(fmt.Printf("Max cookie size %d cannot be less than %d \n", c.HostCookie.MaxCookieSizeBytes, MIN_COOKIE_SIZE_BYTES)) return nil, err } @@ -815,7 +815,7 @@ func New(v *viper.Viper, bidderInfos BidderInfos, normalizeBidderName openrtb_ex } c.BidderInfos = mergedBidderInfos - glog.Info("Logging the resolved configuration:") + di.Log.Info("Logging the resolved configuration:") logGeneral(reflect.ValueOf(c), " \t") if errs := c.validate(v); len(errs) > 0 { return &c, errortypes.NewAggregateError("validation errors", errs) @@ -858,7 +858,7 @@ func setConfigBidderInfoNillableFields(v *viper.Viper, bidderInfos BidderInfos) func (cfg *Configuration) MarshalAccountDefaults() error { var err error if cfg.accountDefaultsJSON, err = jsonutil.Marshal(cfg.AccountDefaults); err != nil { - glog.Warningf("converting %+v to json: %v", cfg.AccountDefaults, err) + di.Log.Warningf("converting %+v to json: %v", cfg.AccountDefaults, err) } return err } diff --git a/config/stored_requests.go b/config/stored_requests.go index 9a3ab260ec2..39f135e5295 100644 --- a/config/stored_requests.go +++ b/config/stored_requests.go @@ -5,7 +5,7 @@ import ( "strings" "time" - "github.com/golang/glog" + "github.com/prebid/prebid-server/v3/di" ) // DataType constants @@ -357,7 +357,7 @@ func (cfg *InMemoryCache) validate(dataType DataType, errs []error) []error { errs = append(errs, fmt.Errorf("%s: in_memory_cache.size_bytes must be >= 0 when in_memory_cache.type=lru. Got %d", section, cfg.Size)) } if cfg.RequestCacheSize > 0 || cfg.ImpCacheSize > 0 || cfg.RespCacheSize > 0 { - glog.Warningf("%s: in_memory_cache.request_cache_size_bytes, imp_cache_size_bytes and resp_cache_size_bytes do not apply to this section and will be ignored", section) + di.Log.Warningf("%s: in_memory_cache.request_cache_size_bytes, imp_cache_size_bytes and resp_cache_size_bytes do not apply to this section and will be ignored", section) } } else { // dual (request and imp) caches @@ -371,7 +371,7 @@ func (cfg *InMemoryCache) validate(dataType DataType, errs []error) []error { errs = append(errs, fmt.Errorf("%s: in_memory_cache.resp_cache_size_bytes must be >= 0 when in_memory_cache.type=lru. Got %d", section, cfg.RespCacheSize)) } if cfg.Size > 0 { - glog.Warningf("%s: in_memory_cache.size_bytes does not apply in this section and will be ignored", section) + di.Log.Warningf("%s: in_memory_cache.size_bytes does not apply in this section and will be ignored", section) } } default: diff --git a/config/structlog.go b/config/structlog.go index 911f475717d..d1e96b0968e 100644 --- a/config/structlog.go +++ b/config/structlog.go @@ -6,7 +6,7 @@ import ( "regexp" "strings" - "github.com/golang/glog" + "github.com/prebid/prebid-server/v3/di" ) type logMsg func(string, ...interface{}) @@ -20,7 +20,7 @@ var blocklistregexp = []*regexp.Regexp{ // prefix if you want that name to be logged. Structs will append . recursively to the prefix // to document deeper structure. func logGeneral(v reflect.Value, prefix string) { - logGeneralWithLogger(v, prefix, glog.Infof) + logGeneralWithLogger(v, prefix, di.Log.Infof) } func logGeneralWithLogger(v reflect.Value, prefix string, logger logMsg) { @@ -45,7 +45,7 @@ func logGeneralWithLogger(v reflect.Value, prefix string, logger logMsg) { func logStructWithLogger(v reflect.Value, prefix string, logger logMsg) { if v.Kind() != reflect.Struct { - glog.Fatalf("LogStruct called on type %s, whuch is not a struct!", v.Type().String()) + di.Log.Fatalf("LogStruct called on type %s, whuch is not a struct!", v.Type().String()) } t := v.Type() for i := 0; i < t.NumField(); i++ { @@ -60,7 +60,7 @@ func logStructWithLogger(v reflect.Value, prefix string, logger logMsg) { func logMapWithLogger(v reflect.Value, prefix string, logger logMsg) { if v.Kind() != reflect.Map { - glog.Fatalf("LogMap called on type %s, whuch is not a map!", v.Type().String()) + di.Log.Fatalf("LogMap called on type %s, whuch is not a map!", v.Type().String()) } for _, k := range v.MapKeys() { if k.Kind() == reflect.String && !allowedName(k.String()) { diff --git a/currency/rate_converter.go b/currency/rate_converter.go index 2e39b57f403..3e74d6c342f 100644 --- a/currency/rate_converter.go +++ b/currency/rate_converter.go @@ -7,7 +7,7 @@ import ( "sync/atomic" "time" - "github.com/golang/glog" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/errortypes" "github.com/prebid/prebid-server/v3/util/jsonutil" "github.com/prebid/prebid-server/v3/util/timeutil" @@ -83,9 +83,9 @@ func (rc *RateConverter) update() error { } else { if rc.checkStaleRates() { rc.clearRates() - glog.Errorf("Error updating conversion rates, falling back to constant rates: %v", err) + di.Log.Errorf("Error updating conversion rates, falling back to constant rates: %v", err) } else { - glog.Errorf("Error updating conversion rates: %v", err) + di.Log.Errorf("Error updating conversion rates: %v", err) } } diff --git a/di/di.go b/di/di.go new file mode 100644 index 00000000000..12b6ee3cfa6 --- /dev/null +++ b/di/di.go @@ -0,0 +1,8 @@ +package di + +import ( + "github.com/prebid/prebid-server/v3/di/interfaces" + "github.com/prebid/prebid-server/v3/di/providers/log" +) + +var Log interfaces.ILogger = log.ProvideLogger() diff --git a/di/interfaces/log.go b/di/interfaces/log.go new file mode 100644 index 00000000000..409f47228bf --- /dev/null +++ b/di/interfaces/log.go @@ -0,0 +1,18 @@ +package interfaces + +type ILogger interface { + Info(args ...any) + Infof(format string, args ...any) + + Warning(args ...any) + Warningf(format string, args ...any) + Warningln(args ...any) + + Error(args ...any) + Errorf(format string, args ...any) + + Exitf(format string, args ...any) + + Fatal(args ...any) + Fatalf(format string, args ...any) +} diff --git a/di/providers/log/alternative.go b/di/providers/log/alternative.go new file mode 100644 index 00000000000..821bc5ab119 --- /dev/null +++ b/di/providers/log/alternative.go @@ -0,0 +1,74 @@ +//go:build custom_logger + +package log + +import ( + "fmt" + "log/slog" + "os" + + "github.com/prebid/prebid-server/v3/di/interfaces" +) + +type SlogWrapper struct { + depth int +} + +func (logger *SlogWrapper) Info(args ...any) { + msg := fmt.Sprint(args...) + slog.Info(msg) +} + +func (logger *SlogWrapper) Infof(format string, args ...any) { + msg := fmt.Sprintf(format, args...) + slog.Info(msg) +} + +func (logger *SlogWrapper) Warning(args ...any) { + msg := fmt.Sprint(args...) + slog.Warn(msg) +} + +func (logger *SlogWrapper) Warningf(format string, args ...any) { + msg := fmt.Sprintf(format, args...) + slog.Warn(msg) +} + +func (logger *SlogWrapper) Warningln(args ...any) { + msg := fmt.Sprintln(args...) + slog.Warn(msg) +} + +func (logger *SlogWrapper) Error(args ...any) { + msg := fmt.Sprint(args...) + slog.Error(msg) +} + +func (logger *SlogWrapper) Errorf(format string, args ...any) { + msg := fmt.Sprintf(format, args...) + slog.Error(msg) +} + +func (logger *SlogWrapper) Exitf(format string, args ...any) { + msg := fmt.Sprintf(format, args...) + slog.Info(msg) + os.Exit(1) +} + +func (logger *SlogWrapper) Fatal(args ...any) { + msg := fmt.Sprint(args...) + slog.Error(msg) + os.Exit(1) +} + +func (logger *SlogWrapper) Fatalf(format string, args ...any) { + msg := fmt.Sprintf(format, args...) + slog.Error(msg) + os.Exit(1) +} + +var logInstance = &SlogWrapper{1} + +func ProvideLogger() interfaces.ILogger { + return logInstance +} diff --git a/di/providers/log/default.go b/di/providers/log/default.go new file mode 100644 index 00000000000..152d7d4e2aa --- /dev/null +++ b/di/providers/log/default.go @@ -0,0 +1,58 @@ +//go:build !custom_logger + +package log + +import ( + "github.com/golang/glog" + "github.com/prebid/prebid-server/v3/di/interfaces" +) + +type GlogWrapper struct { + depth int +} + +func (logger *GlogWrapper) Info(args ...any) { + glog.InfoDepth(logger.depth, args...) +} + +func (logger *GlogWrapper) Infof(format string, args ...any) { + glog.InfoDepthf(logger.depth, format, args...) +} + +func (logger *GlogWrapper) Warning(args ...any) { + glog.WarningDepth(logger.depth, args...) +} + +func (logger *GlogWrapper) Warningf(format string, args ...any) { + glog.WarningDepthf(logger.depth, format, args...) +} + +func (logger *GlogWrapper) Warningln(args ...any) { + glog.WarningDepth(logger.depth, args...) +} + +func (logger *GlogWrapper) Error(args ...any) { + glog.ErrorDepth(logger.depth, args...) +} + +func (logger *GlogWrapper) Errorf(format string, args ...any) { + glog.ErrorDepthf(logger.depth, format, args...) +} + +func (logger *GlogWrapper) Exitf(format string, args ...any) { + glog.ExitDepthf(logger.depth, format, args...) +} + +func (logger *GlogWrapper) Fatal(args ...any) { + glog.FatalDepth(logger.depth, args...) +} + +func (logger *GlogWrapper) Fatalf(format string, args ...any) { + glog.FatalDepthf(logger.depth, format, args...) +} + +var logInstance = &GlogWrapper{1} + +func ProvideLogger() interfaces.ILogger { + return logInstance +} diff --git a/endpoints/cookie_sync.go b/endpoints/cookie_sync.go index 51fe8d57514..c0cd0ae1863 100644 --- a/endpoints/cookie_sync.go +++ b/endpoints/cookie_sync.go @@ -12,13 +12,13 @@ import ( "strings" "time" - "github.com/golang/glog" "github.com/julienschmidt/httprouter" gpplib "github.com/prebid/go-gpp" gppConstants "github.com/prebid/go-gpp/constants" accountService "github.com/prebid/prebid-server/v3/account" "github.com/prebid/prebid-server/v3/analytics" "github.com/prebid/prebid-server/v3/config" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/errortypes" "github.com/prebid/prebid-server/v3/gdpr" "github.com/prebid/prebid-server/v3/macros" @@ -450,7 +450,7 @@ func (c *cookieSyncEndpoint) handleResponse(w http.ResponseWriter, tf usersync.S syncTypes := tf.ForBidder(syncerChoice.Bidder) sync, err := syncerChoice.Syncer.GetSync(syncTypes, m) if err != nil { - glog.Errorf("Failed to get usersync info for %s: %v", syncerChoice.Bidder, err) + di.Log.Errorf("Failed to get usersync info for %s: %v", syncerChoice.Bidder, err) continue } diff --git a/endpoints/currency_rates.go b/endpoints/currency_rates.go index 9d27fb2497d..1b99584a6c1 100644 --- a/endpoints/currency_rates.go +++ b/endpoints/currency_rates.go @@ -4,8 +4,8 @@ import ( "net/http" "time" - "github.com/golang/glog" "github.com/prebid/prebid-server/v3/currency" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/util/jsonutil" ) @@ -62,7 +62,7 @@ func NewCurrencyRatesEndpoint(rateConverter rateConverter, fetchingInterval time return func(w http.ResponseWriter, _ *http.Request) { jsonOutput, err := jsonutil.Marshal(currencyRateInfo) if err != nil { - glog.Errorf("/currency/rates Critical error when trying to marshal currencyRateInfo: %v", err) + di.Log.Errorf("/currency/rates Critical error when trying to marshal currencyRateInfo: %v", err) w.WriteHeader(http.StatusInternalServerError) return } diff --git a/endpoints/events/vtrack.go b/endpoints/events/vtrack.go index 590243bb5c2..b65a19e2979 100644 --- a/endpoints/events/vtrack.go +++ b/endpoints/events/vtrack.go @@ -9,11 +9,11 @@ import ( "strings" "time" - "github.com/golang/glog" "github.com/julienschmidt/httprouter" accountService "github.com/prebid/prebid-server/v3/account" "github.com/prebid/prebid-server/v3/analytics" "github.com/prebid/prebid-server/v3/config" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/errortypes" "github.com/prebid/prebid-server/v3/metrics" "github.com/prebid/prebid-server/v3/openrtb_ext" @@ -213,7 +213,7 @@ func (v *vtrackEndpoint) handleVTrackRequest(ctx context.Context, req *BidCacheR // handle pbs caching errors if len(errs) != 0 { - glog.Errorf("Error(s) updating vast: %v", errs) + di.Log.Errorf("Error(s) updating vast: %v", errs) return nil, errs } diff --git a/endpoints/info/bidders.go b/endpoints/info/bidders.go index 163f6cee5bd..132572597ae 100644 --- a/endpoints/info/bidders.go +++ b/endpoints/info/bidders.go @@ -5,9 +5,9 @@ import ( "sort" "strings" - "github.com/golang/glog" "github.com/julienschmidt/httprouter" "github.com/prebid/prebid-server/v3/config" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/util/jsonutil" ) @@ -18,22 +18,22 @@ var invalidBaseAdaptersOnlyMsg = []byte(`Invalid value for 'baseadaptersonly' qu func NewBiddersEndpoint(bidders config.BidderInfos) httprouter.Handle { responseAll, err := prepareBiddersResponseAll(bidders) if err != nil { - glog.Fatalf("error creating /info/bidders endpoint all bidders response: %v", err) + di.Log.Fatalf("error creating /info/bidders endpoint all bidders response: %v", err) } responseAllBaseOnly, err := prepareBiddersResponseAllBaseOnly(bidders) if err != nil { - glog.Fatalf("error creating /info/bidders endpoint all bidders (base adapters only) response: %v", err) + di.Log.Fatalf("error creating /info/bidders endpoint all bidders (base adapters only) response: %v", err) } responseEnabledOnly, err := prepareBiddersResponseEnabledOnly(bidders) if err != nil { - glog.Fatalf("error creating /info/bidders endpoint enabled only response: %v", err) + di.Log.Fatalf("error creating /info/bidders endpoint enabled only response: %v", err) } responseEnabledOnlyBaseOnly, err := prepareBiddersResponseEnabledOnlyBaseOnly(bidders) if err != nil { - glog.Fatalf("error creating /info/bidders endpoint enabled only (base adapters only) response: %v", err) + di.Log.Fatalf("error creating /info/bidders endpoint enabled only (base adapters only) response: %v", err) } return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { @@ -137,6 +137,6 @@ func writeResponse(w http.ResponseWriter, data []byte) { func writeWithErrorHandling(w http.ResponseWriter, data []byte) { if _, err := w.Write(data); err != nil { - glog.Errorf("error writing response to /info/bidders: %v", err) + di.Log.Errorf("error writing response to /info/bidders: %v", err) } } diff --git a/endpoints/info/bidders_detail.go b/endpoints/info/bidders_detail.go index fb9ce252167..dbc4ed41806 100644 --- a/endpoints/info/bidders_detail.go +++ b/endpoints/info/bidders_detail.go @@ -6,9 +6,9 @@ import ( "net/http" "strings" - "github.com/golang/glog" "github.com/julienschmidt/httprouter" "github.com/prebid/prebid-server/v3/config" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/openrtb_ext" "github.com/prebid/prebid-server/v3/util/jsonutil" ) @@ -22,7 +22,7 @@ const ( func NewBiddersDetailEndpoint(bidders config.BidderInfos) httprouter.Handle { responses, err := prepareBiddersDetailResponse(bidders) if err != nil { - glog.Fatalf("error creating /info/bidders/ endpoint response: %v", err) + di.Log.Fatalf("error creating /info/bidders/ endpoint response: %v", err) } return func(w http.ResponseWriter, _ *http.Request, ps httprouter.Params) { @@ -36,7 +36,7 @@ func NewBiddersDetailEndpoint(bidders config.BidderInfos) httprouter.Handle { if response, ok := responses[bidderName]; ok { w.Header().Set("Content-Type", "application/json") if _, err := w.Write(response); err != nil { - glog.Errorf("error writing response to /info/bidders/%s: %v", bidder, err) + di.Log.Errorf("error writing response to /info/bidders/%s: %v", bidder, err) } } else { w.WriteHeader(http.StatusNotFound) diff --git a/endpoints/openrtb2/amp_auction.go b/endpoints/openrtb2/amp_auction.go index b596ec793c6..58f9994868e 100644 --- a/endpoints/openrtb2/amp_auction.go +++ b/endpoints/openrtb2/amp_auction.go @@ -12,10 +12,10 @@ import ( "time" "github.com/buger/jsonparser" - "github.com/golang/glog" "github.com/julienschmidt/httprouter" "github.com/prebid/openrtb/v20/openrtb2" "github.com/prebid/openrtb/v20/openrtb3" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/hooks/hookexecution" "github.com/prebid/prebid-server/v3/ortb" "github.com/prebid/prebid-server/v3/util/uuidutil" @@ -293,7 +293,7 @@ func (deps *endpointDeps) AmpAuction(w http.ResponseWriter, r *http.Request, _ h if err != nil && !isRejectErr { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "Critical error while running the auction: %v", err) - glog.Errorf("/openrtb2/amp Critical error: %v", err) + di.Log.Errorf("/openrtb2/amp Critical error: %v", err) ao.Status = http.StatusInternalServerError ao.Errors = append(ao.Errors, err) return @@ -304,7 +304,7 @@ func (deps *endpointDeps) AmpAuction(w http.ResponseWriter, r *http.Request, _ h if err := reqWrapper.RebuildRequest(); err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "Critical error while running the auction: %v", err) - glog.Errorf("/openrtb2/amp Critical error: %v", err) + di.Log.Errorf("/openrtb2/amp Critical error: %v", err) ao.Status = http.StatusInternalServerError ao.Errors = append(ao.Errors, err) return @@ -368,7 +368,7 @@ func sendAmpResponse( if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "Critical error while unpacking AMP targets: %v", err) - glog.Errorf("/openrtb2/amp Critical error unpacking targets: %v", err) + di.Log.Errorf("/openrtb2/amp Critical error unpacking targets: %v", err) ao.Errors = append(ao.Errors, fmt.Errorf("Critical error while unpacking AMP targets: %v", err)) ao.Status = http.StatusInternalServerError return labels, ao @@ -468,7 +468,7 @@ func getExtBidResponse( if extResponse.Debug != nil { extBidResponse.Debug = extResponse.Debug } else { - glog.Errorf("Test set on request but debug not present in response.") + di.Log.Errorf("Test set on request but debug not present in response.") ao.Errors = append(ao.Errors, fmt.Errorf("test set on request but debug not present in response")) } } @@ -478,7 +478,7 @@ func getExtBidResponse( modules, warns, err := hookexecution.GetModulesJSON(stageOutcomes, reqWrapper.BidRequest, account) if err != nil { err := fmt.Errorf("Failed to get modules outcome: %s", err) - glog.Errorf(err.Error()) + di.Log.Errorf(err.Error()) ao.Errors = append(ao.Errors, err) } else if modules != nil { extBidResponse.Prebid = &openrtb_ext.ExtResponsePrebid{Modules: modules} diff --git a/endpoints/openrtb2/auction.go b/endpoints/openrtb2/auction.go index e4faa7e9cb8..d4651b81f23 100644 --- a/endpoints/openrtb2/auction.go +++ b/endpoints/openrtb2/auction.go @@ -16,13 +16,13 @@ import ( "github.com/buger/jsonparser" "github.com/gofrs/uuid" - "github.com/golang/glog" "github.com/julienschmidt/httprouter" gpplib "github.com/prebid/go-gpp" "github.com/prebid/go-gpp/constants" "github.com/prebid/openrtb/v20/openrtb2" "github.com/prebid/openrtb/v20/openrtb3" "github.com/prebid/prebid-server/v3/bidadjustment" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/hooks" "github.com/prebid/prebid-server/v3/ortb" "github.com/prebid/prebid-server/v3/privacy" @@ -284,7 +284,7 @@ func (deps *endpointDeps) Auction(w http.ResponseWriter, r *http.Request, _ http labels.RequestStatus = metrics.RequestStatusErr w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "Critical error while running the auction: %v", err) - glog.Errorf("/openrtb2/auction Critical error: %v", err) + di.Log.Errorf("/openrtb2/auction Critical error: %v", err) ao.Status = http.StatusInternalServerError ao.Errors = append(ao.Errors, err) return @@ -295,7 +295,7 @@ func (deps *endpointDeps) Auction(w http.ResponseWriter, r *http.Request, _ http err = setSeatNonBidRaw(req, auctionResponse) if err != nil { - glog.Errorf("Error setting seat non-bid: %v", err) + di.Log.Errorf("Error setting seat non-bid: %v", err) } labels, ao = sendAuctionResponse(w, hookExecutor, response, req.BidRequest, account, labels, ao) } @@ -365,7 +365,7 @@ func sendAuctionResponse( ext, warns, err := hookexecution.EnrichExtBidResponse(response.Ext, stageOutcomes, request, account) if err != nil { err = fmt.Errorf("Failed to enrich Bid Response with hook debug information: %s", err) - glog.Errorf(err.Error()) + di.Log.Errorf(err.Error()) ao.Errors = append(ao.Errors, err) } else { response.Ext = ext @@ -459,7 +459,7 @@ func (deps *endpointDeps) parseRequest(httpRequest *http.Request, labels *metric if rejectErr != nil { errs = []error{rejectErr} if err = jsonutil.UnmarshalValid(requestJson, req.BidRequest); err != nil { - glog.Errorf("Failed to unmarshal BidRequest during entrypoint rejection: %s", err) + di.Log.Errorf("Failed to unmarshal BidRequest during entrypoint rejection: %s", err) } return } @@ -507,7 +507,7 @@ func (deps *endpointDeps) parseRequest(httpRequest *http.Request, labels *metric if rejectErr != nil { errs = []error{rejectErr} if err = jsonutil.UnmarshalValid(requestJson, req.BidRequest); err != nil { - glog.Errorf("Failed to unmarshal BidRequest during raw auction stage rejection: %s", err) + di.Log.Errorf("Failed to unmarshal BidRequest during raw auction stage rejection: %s", err) } return } diff --git a/endpoints/openrtb2/video_auction.go b/endpoints/openrtb2/video_auction.go index cf18840fbd6..634b737de77 100644 --- a/endpoints/openrtb2/video_auction.go +++ b/endpoints/openrtb2/video_auction.go @@ -14,9 +14,9 @@ import ( "github.com/buger/jsonparser" "github.com/gofrs/uuid" - "github.com/golang/glog" "github.com/julienschmidt/httprouter" "github.com/prebid/openrtb/v20/openrtb2" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/hooks" "github.com/prebid/prebid-server/v3/hooks/hookexecution" "github.com/prebid/prebid-server/v3/ortb" @@ -364,7 +364,7 @@ func (deps *endpointDeps) VideoAuctionEndpoint(w http.ResponseWriter, r *http.Re if bidReq.Test == 1 { err = setSeatNonBidRaw(bidReqWrapper, auctionResponse) if err != nil { - glog.Errorf("Error setting seat non-bid: %v", err) + di.Log.Errorf("Error setting seat non-bid: %v", err) } bidResp.Ext = response.Ext } @@ -434,7 +434,7 @@ func handleError(labels *metrics.Labels, w http.ResponseWriter, errL []error, vo w.WriteHeader(status) vo.Status = status fmt.Fprintf(w, "Critical error while running the video endpoint: %v", errors) - glog.Errorf("/openrtb2/video Critical error: %v", errors) + di.Log.Errorf("/openrtb2/video Critical error: %v", errors) vo.Errors = append(vo.Errors, errL...) } diff --git a/endpoints/version.go b/endpoints/version.go index 8eb305c3f5e..bb1aaef99ed 100644 --- a/endpoints/version.go +++ b/endpoints/version.go @@ -4,7 +4,7 @@ import ( "encoding/json" "net/http" - "github.com/golang/glog" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/util/jsonutil" ) @@ -14,7 +14,7 @@ const versionEndpointValueNotSet = "not-set" func NewVersionEndpoint(version, revision string) http.HandlerFunc { response, err := prepareVersionEndpointResponse(version, revision) if err != nil { - glog.Fatalf("error creating /version endpoint response: %v", err) + di.Log.Fatalf("error creating /version endpoint response: %v", err) } return func(w http.ResponseWriter, _ *http.Request) { diff --git a/exchange/bidder.go b/exchange/bidder.go index 232da470fba..bd565d0ccca 100644 --- a/exchange/bidder.go +++ b/exchange/bidder.go @@ -16,10 +16,10 @@ import ( "sync" "time" - "github.com/golang/glog" "github.com/prebid/prebid-server/v3/bidadjustment" "github.com/prebid/prebid-server/v3/config/util" "github.com/prebid/prebid-server/v3/currency" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/exchange/entities" "github.com/prebid/prebid-server/v3/experiment/adscert" "github.com/prebid/prebid-server/v3/hooks/hookexecution" @@ -527,7 +527,7 @@ func makeExt(httpInfo *httpCallInfo) *openrtb_ext.ExtHttpCall { // doRequest makes a request, handles the response, and returns the data needed by the // Bidder interface. func (bidder *BidderAdapter) doRequest(ctx context.Context, req *adapters.RequestData, bidderRequestStartTime time.Time, tmaxAdjustments *TmaxAdjustmentsPreprocessed) *httpCallInfo { - return bidder.doRequestImpl(ctx, req, glog.Warningf, bidderRequestStartTime, tmaxAdjustments) + return bidder.doRequestImpl(ctx, req, di.Log.Warningf, bidderRequestStartTime, tmaxAdjustments) } func (bidder *BidderAdapter) doRequestImpl(ctx context.Context, req *adapters.RequestData, logger util.LogMsg, bidderRequestStartTime time.Time, tmaxAdjustments *TmaxAdjustmentsPreprocessed) *httpCallInfo { diff --git a/exchange/bidder_test.go b/exchange/bidder_test.go index dbb167e053d..39b6e162d85 100644 --- a/exchange/bidder_test.go +++ b/exchange/bidder_test.go @@ -21,7 +21,6 @@ import ( "testing" "time" - "github.com/golang/glog" "github.com/prebid/openrtb/v20/adcom1" nativeRequests "github.com/prebid/openrtb/v20/native1/request" nativeResponse "github.com/prebid/openrtb/v20/native1/response" @@ -29,6 +28,7 @@ import ( "github.com/prebid/prebid-server/v3/adapters" "github.com/prebid/prebid-server/v3/config" "github.com/prebid/prebid-server/v3/currency" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/errortypes" "github.com/prebid/prebid-server/v3/exchange/entities" "github.com/prebid/prebid-server/v3/experiment/adscert" @@ -2210,7 +2210,7 @@ func TestTimeoutNotificationOff(t *testing.T) { if tb, ok := bidder.Bidder.(adapters.TimeoutBidder); !ok { t.Error("Failed to cast bidder to a TimeoutBidder") } else { - bidder.doTimeoutNotification(tb, &adapters.RequestData{}, glog.Warningf) + bidder.doTimeoutNotification(tb, &adapters.RequestData{}, di.Log.Warningf) } } diff --git a/exchange/exchange.go b/exchange/exchange.go index 9ab91ee9ea3..5bc4a6a18e2 100644 --- a/exchange/exchange.go +++ b/exchange/exchange.go @@ -42,9 +42,9 @@ import ( "github.com/buger/jsonparser" "github.com/gofrs/uuid" - "github.com/golang/glog" "github.com/prebid/openrtb/v20/openrtb2" "github.com/prebid/openrtb/v20/openrtb3" + "github.com/prebid/prebid-server/v3/di" ) type extCacheInstructions struct { @@ -728,7 +728,7 @@ func (e *exchange) getAllBids( bidderRunner := e.recoverSafely(bidderRequests, func(bidderRequest BidderRequest, conversions currency.Conversions) { // Passing in aName so a doesn't change out from under the go routine if bidderRequest.BidderLabels.Adapter == "" { - glog.Errorf("Exchange: bidlables for %s (%s) missing adapter string", bidderRequest.BidderName, bidderRequest.BidderCoreName) + di.Log.Errorf("Exchange: bidlables for %s (%s) missing adapter string", bidderRequest.BidderName, bidderRequest.BidderCoreName) bidderRequest.BidderLabels.Adapter = bidderRequest.BidderCoreName } brw := new(bidResponseWrapper) @@ -857,7 +857,7 @@ func (e *exchange) recoverSafely(bidderRequests []BidderRequest, allBidders = sb.String()[:sb.Len()-1] } - glog.Errorf("OpenRTB auction recovered panic from Bidder %s: %v. "+ + di.Log.Errorf("OpenRTB auction recovered panic from Bidder %s: %v. "+ "Account id: %s, All Bidders: %s, Stack trace is: %v", bidderRequest.BidderCoreName, r, bidderRequest.BidderLabels.PubID, allBidders, string(debug.Stack())) e.me.RecordAdapterPanic(bidderRequest.BidderLabels) diff --git a/experiment/adscert/SignerLogger.go b/experiment/adscert/SignerLogger.go index 1d99bcc63f5..b5a80d523be 100644 --- a/experiment/adscert/SignerLogger.go +++ b/experiment/adscert/SignerLogger.go @@ -2,7 +2,7 @@ package adscert import ( "fmt" - "github.com/golang/glog" + "github.com/prebid/prebid-server/v3/di" ) type SignerLogger struct { @@ -10,27 +10,27 @@ type SignerLogger struct { func (sl *SignerLogger) Debugf(format string, args ...interface{}) { //there is no Debug level in glog - glog.Infof(format, args...) + di.Log.Infof(format, args...) } func (sl *SignerLogger) Infof(format string, args ...interface{}) { - glog.Infof(format, args...) + di.Log.Infof(format, args...) } func (sl *SignerLogger) Info(format string) { - glog.Info(format) + di.Log.Info(format) } func (sl *SignerLogger) Warningf(format string, args ...interface{}) { - glog.Warningf(format, args...) + di.Log.Warningf(format, args...) } func (sl *SignerLogger) Errorf(format string, args ...interface{}) { - glog.Errorf(format, args...) + di.Log.Errorf(format, args...) } func (sl *SignerLogger) Fatalf(format string, args ...interface{}) { - glog.Fatalf(format, args...) + di.Log.Fatalf(format, args...) } func (sl *SignerLogger) Panicf(format string, args ...interface{}) { diff --git a/floors/fetcher.go b/floors/fetcher.go index 9fa6ad4f380..78c04299cea 100644 --- a/floors/fetcher.go +++ b/floors/fetcher.go @@ -14,8 +14,8 @@ import ( "github.com/alitto/pond" validator "github.com/asaskevich/govalidator" "github.com/coocood/freecache" - "github.com/golang/glog" "github.com/prebid/prebid-server/v3/config" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/metrics" "github.com/prebid/prebid-server/v3/openrtb_ext" "github.com/prebid/prebid-server/v3/util/timeutil" @@ -90,7 +90,7 @@ func (fq *FetchQueue) Top() *fetchInfo { } func workerPanicHandler(p interface{}) { - glog.Errorf("floor fetcher worker panicked: %v", p) + di.Log.Errorf("floor fetcher worker panicked: %v", p) } func NewPriceFloorFetcher(config config.PriceFloors, httpClient *http.Client, metricEngine metrics.MetricsEngine) *PriceFloorFetcher { @@ -165,7 +165,7 @@ func (f *PriceFloorFetcher) worker(fetchConfig fetchInfo) { } floorData, err := json.Marshal(floorData) if err != nil { - glog.Errorf("Error while marshaling fetched floor data for url %s", fetchConfig.AccountFloorFetch.URL) + di.Log.Errorf("Error while marshaling fetched floor data for url %s", fetchConfig.AccountFloorFetch.URL) } else { f.SetWithExpiry(fetchConfig.AccountFloorFetch.URL, floorData, cacheExpiry) } @@ -224,7 +224,7 @@ func (f *PriceFloorFetcher) Fetcher() { } case <-f.done: ticker.Stop() - glog.Info("Price Floor fetcher terminated") + di.Log.Info("Price Floor fetcher terminated") return } } @@ -233,23 +233,23 @@ func (f *PriceFloorFetcher) Fetcher() { func (f *PriceFloorFetcher) fetchAndValidate(config config.AccountFloorFetch) (*openrtb_ext.PriceFloorRules, int) { floorResp, maxAge, err := f.fetchFloorRulesFromURL(config) if floorResp == nil || err != nil { - glog.Errorf("Error while fetching floor data from URL: %s, reason : %s", config.URL, err.Error()) + di.Log.Errorf("Error while fetching floor data from URL: %s, reason : %s", config.URL, err.Error()) return nil, 0 } if len(floorResp) > (config.MaxFileSizeKB * 1024) { - glog.Errorf("Recieved invalid floor data from URL: %s, reason : floor file size is greater than MaxFileSize", config.URL) + di.Log.Errorf("Recieved invalid floor data from URL: %s, reason : floor file size is greater than MaxFileSize", config.URL) return nil, 0 } var priceFloors openrtb_ext.PriceFloorRules if err = json.Unmarshal(floorResp, &priceFloors.Data); err != nil { - glog.Errorf("Recieved invalid price floor json from URL: %s", config.URL) + di.Log.Errorf("Recieved invalid price floor json from URL: %s", config.URL) return nil, 0 } if err := validateRules(config, &priceFloors); err != nil { - glog.Errorf("Validation failed for floor JSON from URL: %s, reason: %s", config.URL, err.Error()) + di.Log.Errorf("Validation failed for floor JSON from URL: %s, reason: %s", config.URL, err.Error()) return nil, 0 } @@ -280,10 +280,10 @@ func (f *PriceFloorFetcher) fetchFloorRulesFromURL(config config.AccountFloorFet if maxAgeStr := httpResp.Header.Get("max-age"); maxAgeStr != "" { maxAge, err = strconv.Atoi(maxAgeStr) if err != nil { - glog.Errorf("max-age in header is malformed for url %s", config.URL) + di.Log.Errorf("max-age in header is malformed for url %s", config.URL) } if maxAge <= config.Period || maxAge > math.MaxInt32 { - glog.Errorf("Invalid max-age = %s provided, value should be valid integer and should be within (%v, %v)", maxAgeStr, config.Period, math.MaxInt32) + di.Log.Errorf("Invalid max-age = %s provided, value should be valid integer and should be within (%v, %v)", maxAgeStr, config.Period, math.MaxInt32) } } diff --git a/floors/rule.go b/floors/rule.go index 65ddf31e727..a537d65ee05 100644 --- a/floors/rule.go +++ b/floors/rule.go @@ -7,9 +7,9 @@ import ( "sort" "strings" - "github.com/golang/glog" "github.com/prebid/openrtb/v20/openrtb2" "github.com/prebid/prebid-server/v3/currency" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/openrtb_ext" "github.com/prebid/prebid-server/v3/util/ptrutil" ) @@ -74,7 +74,7 @@ func getMinFloorValue(floorExt *openrtb_ext.PriceFloorRules, imp *openrtb_ext.Im floorCur = getFloorCurrency(floorExt) if floorMin > 0.0 && floorMinCur != "" { if floorExt.FloorMinCur != "" && impFloorCur != "" && floorExt.FloorMinCur != impFloorCur { - glog.Warning("FloorMinCur are different in floorExt and ImpExt") + di.Log.Warning("FloorMinCur are different in floorExt and ImpExt") } if floorCur != "" && floorMinCur != floorCur { rate, err = conversions.GetRate(floorMinCur, floorCur) diff --git a/gdpr/vendorlist-fetching.go b/gdpr/vendorlist-fetching.go index dc035483479..4e80132f068 100644 --- a/gdpr/vendorlist-fetching.go +++ b/gdpr/vendorlist-fetching.go @@ -10,11 +10,11 @@ import ( "sync/atomic" "time" - "github.com/golang/glog" "github.com/prebid/go-gdpr/api" "github.com/prebid/go-gdpr/vendorlist" "github.com/prebid/go-gdpr/vendorlist2" "github.com/prebid/prebid-server/v3/config" + "github.com/prebid/prebid-server/v3/di" "golang.org/x/net/context/ctxhttp" ) @@ -118,30 +118,30 @@ func newOccasionalSaver(timeout time.Duration) func(ctx context.Context, client func saveOne(ctx context.Context, client *http.Client, url string, saver saveVendors) uint16 { req, err := http.NewRequest("GET", url, nil) if err != nil { - glog.Errorf("Failed to build GET %s request. Cookie syncs may be affected: %v", url, err) + di.Log.Errorf("Failed to build GET %s request. Cookie syncs may be affected: %v", url, err) return 0 } resp, err := ctxhttp.Do(ctx, client, req) if err != nil { - glog.Errorf("Error calling GET %s. Cookie syncs may be affected: %v", url, err) + di.Log.Errorf("Error calling GET %s. Cookie syncs may be affected: %v", url, err) return 0 } defer resp.Body.Close() respBody, err := io.ReadAll(resp.Body) if err != nil { - glog.Errorf("Error reading response body from GET %s. Cookie syncs may be affected: %v", url, err) + di.Log.Errorf("Error reading response body from GET %s. Cookie syncs may be affected: %v", url, err) return 0 } if resp.StatusCode != http.StatusOK { - glog.Errorf("GET %s returned %d. Cookie syncs may be affected.", url, resp.StatusCode) + di.Log.Errorf("GET %s returned %d. Cookie syncs may be affected.", url, resp.StatusCode) return 0 } var newList api.VendorList newList, err = vendorlist2.ParseEagerly(respBody) if err != nil { - glog.Errorf("GET %s returned malformed JSON. Cookie syncs may be affected. Error was %v. Body was %s", url, err, string(respBody)) + di.Log.Errorf("GET %s returned malformed JSON. Cookie syncs may be affected. Error was %v. Body was %s", url, err, string(respBody)) return 0 } diff --git a/hooks/hookexecution/context.go b/hooks/hookexecution/context.go index 98a38714618..e110eff4c97 100644 --- a/hooks/hookexecution/context.go +++ b/hooks/hookexecution/context.go @@ -3,8 +3,8 @@ package hookexecution import ( "sync" - "github.com/golang/glog" "github.com/prebid/prebid-server/v3/config" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/hooks/hookstage" "github.com/prebid/prebid-server/v3/privacy" ) @@ -30,7 +30,7 @@ func (ctx executionContext) getModuleContext(moduleName string) hookstage.Module if ctx.account != nil { cfg, err := ctx.account.Hooks.Modules.ModuleConfig(moduleName) if err != nil { - glog.Warningf("Failed to get account config for %s module: %s", moduleName, err) + di.Log.Warningf("Failed to get account config for %s module: %s", moduleName, err) } moduleInvocationCtx.AccountConfig = cfg diff --git a/hooks/plan.go b/hooks/plan.go index 62655f6cf5c..e2fde81ff40 100644 --- a/hooks/plan.go +++ b/hooks/plan.go @@ -3,8 +3,8 @@ package hooks import ( "time" - "github.com/golang/glog" "github.com/prebid/prebid-server/v3/config" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/hooks/hookstage" ) @@ -198,7 +198,7 @@ func getGroup[T any](getHookFn hookFn[T], cfg config.HookExecutionGroup) Group[T if h, ok := getHookFn(hookCfg.ModuleCode); ok { group.Hooks = append(group.Hooks, HookWrapper[T]{Module: hookCfg.ModuleCode, Code: hookCfg.HookImplCode, Hook: h}) } else { - glog.Warningf("Not found hook while building hook execution plan: %s %s", hookCfg.ModuleCode, hookCfg.HookImplCode) + di.Log.Warningf("Not found hook while building hook execution plan: %s %s", hookCfg.ModuleCode, hookCfg.HookImplCode) } } diff --git a/main.go b/main.go index 0063b4ee0b6..acb504bca1c 100644 --- a/main.go +++ b/main.go @@ -16,7 +16,7 @@ import ( "github.com/prebid/prebid-server/v3/util/jsonutil" "github.com/prebid/prebid-server/v3/util/task" - "github.com/golang/glog" + "github.com/prebid/prebid-server/v3/di" "github.com/spf13/viper" ) @@ -25,20 +25,20 @@ func init() { } func main() { - flag.Parse() // required for glog flags and testing package flags + flag.Parse() // required for di.Log flags and testing package flags bidderInfoPath, err := filepath.Abs(infoDirectory) if err != nil { - glog.Exitf("Unable to build configuration directory path: %v", err) + di.Log.Exitf("Unable to build configuration directory path: %v", err) } bidderInfos, err := config.LoadBidderInfoFromDisk(bidderInfoPath) if err != nil { - glog.Exitf("Unable to load bidder configurations: %v", err) + di.Log.Exitf("Unable to load bidder configurations: %v", err) } cfg, err := loadConfig(bidderInfos) if err != nil { - glog.Exitf("Configuration could not be loaded or did not pass validation: %v", err) + di.Log.Exitf("Configuration could not be loaded or did not pass validation: %v", err) } // Create a soft memory limit on the total amount of memory that PBS uses to tune the behavior @@ -51,7 +51,7 @@ func main() { err = serve(cfg) if err != nil { - glog.Exitf("prebid-server failed: %v", err) + di.Log.Exitf("prebid-server failed: %v", err) } } @@ -79,7 +79,7 @@ func serve(cfg *config.Configuration) error { corsRouter := router.SupportCORS(r) if err := server.Listen(cfg, router.NoCache{Handler: corsRouter}, router.Admin(currencyConverter, fetchingInterval), r.MetricsEngine); err != nil { - glog.Fatalf("prebid-server returned an error: %v", err) + di.Log.Fatalf("prebid-server returned an error: %v", err) } r.Shutdown() diff --git a/metrics/go_metrics.go b/metrics/go_metrics.go index 428b1891e69..81062c35600 100644 --- a/metrics/go_metrics.go +++ b/metrics/go_metrics.go @@ -6,8 +6,8 @@ import ( "sync" "time" - "github.com/golang/glog" "github.com/prebid/prebid-server/v3/config" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/openrtb_ext" metrics "github.com/rcrowley/go-metrics" ) @@ -685,7 +685,7 @@ func (me *Metrics) RecordAdapterPanic(labels AdapterLabels) { lowerCaseAdapterName := strings.ToLower(adapterStr) am, ok := me.AdapterMetrics[lowerCaseAdapterName] if !ok { - glog.Errorf("Trying to run adapter metrics on %s: adapter metrics not found", adapterStr) + di.Log.Errorf("Trying to run adapter metrics on %s: adapter metrics not found", adapterStr) return } am.PanicMeter.Mark(1) @@ -697,7 +697,7 @@ func (me *Metrics) RecordAdapterRequest(labels AdapterLabels) { lowerCaseAdapter := strings.ToLower(adapterStr) am, ok := me.AdapterMetrics[lowerCaseAdapter] if !ok { - glog.Errorf("Trying to run adapter metrics on %s: adapter metrics not found", adapterStr) + di.Log.Errorf("Trying to run adapter metrics on %s: adapter metrics not found", adapterStr) return } @@ -714,7 +714,7 @@ func (me *Metrics) RecordAdapterRequest(labels AdapterLabels) { aam.GotBidsMeter.Mark(1) } default: - glog.Warningf("No go-metrics logged for AdapterBids value: %s", labels.AdapterBids) + di.Log.Warningf("No go-metrics logged for AdapterBids value: %s", labels.AdapterBids) } for errType := range labels.AdapterErrors { am.ErrorMeters[errType].Mark(1) @@ -737,7 +737,7 @@ func (me *Metrics) RecordAdapterConnections(adapterName openrtb_ext.BidderName, lowerCaseAdapterName := strings.ToLower(string(adapterName)) am, ok := me.AdapterMetrics[lowerCaseAdapterName] if !ok { - glog.Errorf("Trying to log adapter connection metrics for %s: adapter not found", string(adapterName)) + di.Log.Errorf("Trying to log adapter connection metrics for %s: adapter not found", string(adapterName)) return } @@ -768,7 +768,7 @@ func (me *Metrics) RecordAdapterBidReceived(labels AdapterLabels, bidType openrt lowerCaseAdapterName := strings.ToLower(adapterStr) am, ok := me.AdapterMetrics[lowerCaseAdapterName] if !ok { - glog.Errorf("Trying to run adapter bid metrics on %s: adapter metrics not found", adapterStr) + di.Log.Errorf("Trying to run adapter bid metrics on %s: adapter metrics not found", adapterStr) return } @@ -786,7 +786,7 @@ func (me *Metrics) RecordAdapterBidReceived(labels AdapterLabels, bidType openrt metricsForType.NurlMeter.Mark(1) } } else { - glog.Errorf("bid/adm metrics map entry does not exist for type %s. This is a bug, and should be reported.", bidType) + di.Log.Errorf("bid/adm metrics map entry does not exist for type %s. This is a bug, and should be reported.", bidType) } } @@ -796,7 +796,7 @@ func (me *Metrics) RecordAdapterPrice(labels AdapterLabels, cpm float64) { lowercaseAdapter := strings.ToLower(adapterStr) am, ok := me.AdapterMetrics[lowercaseAdapter] if !ok { - glog.Errorf("Trying to run adapter price metrics on %s: adapter metrics not found", adapterStr) + di.Log.Errorf("Trying to run adapter price metrics on %s: adapter metrics not found", adapterStr) return } // Adapter metrics @@ -813,7 +813,7 @@ func (me *Metrics) RecordAdapterTime(labels AdapterLabels, length time.Duration) lowercaseAdapter := strings.ToLower(adapterStr) am, ok := me.AdapterMetrics[lowercaseAdapter] if !ok { - glog.Errorf("Trying to run adapter latency metrics on %s: adapter metrics not found", string(labels.Adapter)) + di.Log.Errorf("Trying to run adapter latency metrics on %s: adapter metrics not found", string(labels.Adapter)) return } // Adapter metrics @@ -939,7 +939,7 @@ func (me *Metrics) RecordAdapterBuyerUIDScrubbed(adapterName openrtb_ext.BidderN am, ok := me.AdapterMetrics[strings.ToLower(adapterStr)] if !ok { - glog.Errorf("Trying to log adapter buyeruid scrubbed metric for %s: adapter not found", adapterStr) + di.Log.Errorf("Trying to log adapter buyeruid scrubbed metric for %s: adapter not found", adapterStr) return } @@ -954,7 +954,7 @@ func (me *Metrics) RecordAdapterGDPRRequestBlocked(adapterName openrtb_ext.Bidde am, ok := me.AdapterMetrics[strings.ToLower(adapterStr)] if !ok { - glog.Errorf("Trying to log adapter GDPR request blocked metric for %s: adapter not found", adapterStr) + di.Log.Errorf("Trying to log adapter GDPR request blocked metric for %s: adapter not found", adapterStr) return } @@ -977,7 +977,7 @@ func (me *Metrics) RecordBidValidationCreativeSizeError(adapter openrtb_ext.Bidd adapterStr := string(adapter) am, ok := me.AdapterMetrics[strings.ToLower(adapterStr)] if !ok { - glog.Errorf("Trying to run adapter metrics on %s: adapter metrics not found", adapterStr) + di.Log.Errorf("Trying to run adapter metrics on %s: adapter metrics not found", adapterStr) return } am.BidValidationCreativeSizeErrorMeter.Mark(1) @@ -992,7 +992,7 @@ func (me *Metrics) RecordBidValidationCreativeSizeWarn(adapter openrtb_ext.Bidde adapterStr := string(adapter) am, ok := me.AdapterMetrics[strings.ToLower(adapterStr)] if !ok { - glog.Errorf("Trying to run adapter metrics on %s: adapter metrics not found", adapterStr) + di.Log.Errorf("Trying to run adapter metrics on %s: adapter metrics not found", adapterStr) return } am.BidValidationCreativeSizeWarnMeter.Mark(1) @@ -1007,7 +1007,7 @@ func (me *Metrics) RecordBidValidationSecureMarkupError(adapter openrtb_ext.Bidd adapterStr := string(adapter) am, ok := me.AdapterMetrics[strings.ToLower(adapterStr)] if !ok { - glog.Errorf("Trying to run adapter metrics on %s: adapter metrics not found", adapterStr) + di.Log.Errorf("Trying to run adapter metrics on %s: adapter metrics not found", adapterStr) return } am.BidValidationSecureMarkupErrorMeter.Mark(1) @@ -1022,7 +1022,7 @@ func (me *Metrics) RecordBidValidationSecureMarkupWarn(adapter openrtb_ext.Bidde adapterStr := string(adapter) am, ok := me.AdapterMetrics[strings.ToLower(adapterStr)] if !ok { - glog.Errorf("Trying to run adapter metrics on %s: adapter metrics not found", adapterStr) + di.Log.Errorf("Trying to run adapter metrics on %s: adapter metrics not found", adapterStr) return } am.BidValidationSecureMarkupWarnMeter.Mark(1) @@ -1158,7 +1158,7 @@ func (me *Metrics) getModuleMetric(labels ModuleLabels) (*ModuleMetrics, error) mm, ok := me.ModuleMetrics[labels.Module][labels.Stage] if !ok { err := fmt.Errorf("Trying to run module %s metrics for stage %s: module metrics not found", labels.Module, labels.Stage) - glog.Errorf(err.Error()) + di.Log.Errorf(err.Error()) return nil, err } diff --git a/modules/fiftyonedegrees/devicedetection/device_info_extractor.go b/modules/fiftyonedegrees/devicedetection/device_info_extractor.go index 1c913e21696..2d2d425e003 100644 --- a/modules/fiftyonedegrees/devicedetection/device_info_extractor.go +++ b/modules/fiftyonedegrees/devicedetection/device_info_extractor.go @@ -3,8 +3,8 @@ package devicedetection import ( "strconv" - "github.com/golang/glog" "github.com/pkg/errors" + "github.com/prebid/prebid-server/v3/di" ) // deviceInfoExtractor is a struct that contains the methods to extract device information @@ -102,18 +102,18 @@ func (x deviceInfoExtractor) getValue(results Results, propertyName deviceInfoPr ",", ) if err != nil { - glog.Errorf("Failed to get results values string.") + di.Log.Errorf("Failed to get results values string.") return "" } hasValues, err := results.HasValues(string(propertyName)) if err != nil { - glog.Errorf("Failed to check if a matched value exists for property %s.\n", propertyName) + di.Log.Errorf("Failed to check if a matched value exists for property %s.\n", propertyName) return "" } if !hasValues { - glog.Warningf("Property %s does not have a matched value.\n", propertyName) + di.Log.Warningf("Property %s does not have a matched value.\n", propertyName) return "Unknown" } diff --git a/modules/modules.go b/modules/modules.go index 3b266a14c5b..e0da41392fc 100644 --- a/modules/modules.go +++ b/modules/modules.go @@ -4,8 +4,8 @@ import ( "encoding/json" "fmt" - "github.com/golang/glog" "github.com/prebid/prebid-server/v3/config" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/hooks" "github.com/prebid/prebid-server/v3/modules/moduledeps" "github.com/prebid/prebid-server/v3/util/jsonutil" @@ -71,7 +71,7 @@ func (m *builder) Build( } if !isEnabled { - glog.Infof("Skip %s module, disabled.", id) + di.Log.Infof("Skip %s module, disabled.", id) continue } diff --git a/pbs/usersync.go b/pbs/usersync.go index b8c0572c4ac..8772a92641b 100644 --- a/pbs/usersync.go +++ b/pbs/usersync.go @@ -8,9 +8,9 @@ import ( "net/url" "strings" - "github.com/golang/glog" "github.com/julienschmidt/httprouter" "github.com/prebid/prebid-server/v3/config" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/server/ssl" "github.com/prebid/prebid-server/v3/usersync" ) @@ -69,9 +69,7 @@ func (deps *UserSyncDeps) OptOut(w http.ResponseWriter, r *http.Request, _ httpr err := deps.VerifyRecaptcha(rr) if err != nil { - if glog.V(2) { - glog.Infof("Opt Out failed recaptcha: %v", err) - } + di.Log.Infof("Opt Out failed recaptcha: %v", err) w.WriteHeader(http.StatusUnauthorized) return } diff --git a/prebid_cache_client/client.go b/prebid_cache_client/client.go index a409b4f7d1a..662938a92fa 100644 --- a/prebid_cache_client/client.go +++ b/prebid_cache_client/client.go @@ -16,7 +16,7 @@ import ( "github.com/prebid/prebid-server/v3/metrics" "github.com/buger/jsonparser" - "github.com/golang/glog" + "github.com/prebid/prebid-server/v3/di" "golang.org/x/net/context/ctxhttp" ) @@ -149,7 +149,7 @@ func (c *clientImpl) PutJson(ctx context.Context, values []Cacheable) (uuids []s func logError(errs *[]error, format string, a ...interface{}) { msg := fmt.Sprintf(format, a...) - glog.Error(msg) + di.Log.Error(msg) *errs = append(*errs, errors.New(msg)) } diff --git a/router/router.go b/router/router.go index d412b5152e2..768f1595e64 100644 --- a/router/router.go +++ b/router/router.go @@ -42,9 +42,9 @@ import ( "github.com/prebid/prebid-server/v3/version" _ "github.com/go-sql-driver/mysql" - "github.com/golang/glog" "github.com/julienschmidt/httprouter" _ "github.com/lib/pq" + "github.com/prebid/prebid-server/v3/di" "github.com/rs/cors" ) @@ -66,7 +66,7 @@ func newJsonDirectoryServer(schemaDirectory string, validator openrtb_ext.Bidder // Slurp the files into memory first, since they're small and it minimizes request latency. files, err := os.ReadDir(schemaDirectory) if err != nil { - glog.Fatalf("Failed to read directory %s: %v", schemaDirectory, err) + di.Log.Fatalf("Failed to read directory %s: %v", schemaDirectory, err) } bidderMap := openrtb_ext.BuildBidderMap() @@ -76,7 +76,7 @@ func newJsonDirectoryServer(schemaDirectory string, validator openrtb_ext.Bidder bidder := strings.TrimSuffix(file.Name(), ".json") bidderName, isValid := bidderMap[bidder] if !isValid { - glog.Fatalf("Schema exists for an unknown bidder: %s", bidder) + di.Log.Fatalf("Schema exists for an unknown bidder: %s", bidder) } data[bidder] = json.RawMessage(validator.Schema(bidderName)) } @@ -88,7 +88,7 @@ func newJsonDirectoryServer(schemaDirectory string, validator openrtb_ext.Bidder response, err := jsonutil.Marshal(data) if err != nil { - glog.Fatalf("Failed to marshal bidder param JSON-schema: %v", err) + di.Log.Fatalf("Failed to marshal bidder param JSON-schema: %v", err) } return func(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) { @@ -133,7 +133,7 @@ func New(cfg *config.Configuration, rateConvertor *currency.RateConverter) (r *R var readCertErr error certPool, readCertErr = ssl.AppendPEMFileToRootCAPool(certPool, cfg.PemCertsFile) if readCertErr != nil { - glog.Infof("Could not read certificates file: %s \n", readCertErr.Error()) + di.Log.Infof("Could not read certificates file: %s \n", readCertErr.Error()) } generalHttpClient := &http.Client{ @@ -188,7 +188,7 @@ func New(cfg *config.Configuration, rateConvertor *currency.RateConverter) (r *R moduleDeps := moduledeps.ModuleDeps{HTTPClient: generalHttpClient, RateConvertor: rateConvertor} repo, moduleStageNames, err := modules.NewBuilder().Build(cfg.Hooks.Modules, moduleDeps) if err != nil { - glog.Fatalf("Failed to init hook modules: %v", err) + di.Log.Fatalf("Failed to init hook modules: %v", err) } // Metrics engine @@ -202,7 +202,7 @@ func New(cfg *config.Configuration, rateConvertor *currency.RateConverter) (r *R paramsValidator, err := openrtb_ext.NewBidderParamsValidator(schemaDirectory) if err != nil { - glog.Fatalf("Failed to create the bidder params validator. %v", err) + di.Log.Fatalf("Failed to create the bidder params validator. %v", err) } activeBidders := exchange.GetActiveBidders(cfg.BidderInfos) @@ -224,7 +224,7 @@ func New(cfg *config.Configuration, rateConvertor *currency.RateConverter) (r *R } adsCertSigner, err := adscert.NewAdCertsSigner(cfg.Experiment.AdCerts) if err != nil { - glog.Fatalf("Failed to create ads cert signer: %v", err) + di.Log.Fatalf("Failed to create ads cert signer: %v", err) } requestValidator := ortb.NewRequestValidator(activeBidders, disabledBidders, paramsValidator) @@ -237,17 +237,17 @@ func New(cfg *config.Configuration, rateConvertor *currency.RateConverter) (r *R var uuidGenerator uuidutil.UUIDRandomGenerator openrtbEndpoint, err := openrtb2.NewEndpoint(uuidGenerator, theExchange, requestValidator, fetcher, accounts, cfg, r.MetricsEngine, analyticsRunner, disabledBidders, defReqJSON, activeBidders, storedRespFetcher, planBuilder, tmaxAdjustments) if err != nil { - glog.Fatalf("Failed to create the openrtb2 endpoint handler. %v", err) + di.Log.Fatalf("Failed to create the openrtb2 endpoint handler. %v", err) } ampEndpoint, err := openrtb2.NewAmpEndpoint(uuidGenerator, theExchange, requestValidator, ampFetcher, accounts, cfg, r.MetricsEngine, analyticsRunner, disabledBidders, defReqJSON, activeBidders, storedRespFetcher, planBuilder, tmaxAdjustments) if err != nil { - glog.Fatalf("Failed to create the amp endpoint handler. %v", err) + di.Log.Fatalf("Failed to create the amp endpoint handler. %v", err) } videoEndpoint, err := openrtb2.NewVideoEndpoint(uuidGenerator, theExchange, requestValidator, fetcher, videoFetcher, accounts, cfg, r.MetricsEngine, analyticsRunner, disabledBidders, defReqJSON, activeBidders, cacheClient, tmaxAdjustments) if err != nil { - glog.Fatalf("Failed to create the video endpoint handler. %v", err) + di.Log.Fatalf("Failed to create the video endpoint handler. %v", err) } requestTimeoutHeaders := config.RequestTimeoutHeaders{} @@ -294,11 +294,11 @@ func New(cfg *config.Configuration, rateConvertor *currency.RateConverter) (r *R // Shutdown closes any dependencies of the router that may need closing func (r *Router) Shutdown() { - glog.Info("[PBS Router] shutting down") + di.Log.Info("[PBS Router] shutting down") for _, shutdown := range r.shutdowns { shutdown() } - glog.Info("[PBS Router] shut down") + di.Log.Info("[PBS Router] shut down") } func checkSupportedUserSyncEndpoints(bidderInfos config.BidderInfos) error { @@ -312,11 +312,11 @@ func checkSupportedUserSyncEndpoints(bidderInfos config.BidderInfos) error { switch endpointLower { case "iframe": if info.Syncer.IFrame == nil { - glog.Warningf("bidder %s supports iframe user sync, but doesn't have a default and must be configured by the host", name) + di.Log.Warningf("bidder %s supports iframe user sync, but doesn't have a default and must be configured by the host", name) } case "redirect": if info.Syncer.Redirect == nil { - glog.Warningf("bidder %s supports redirect user sync, but doesn't have a default and must be configured by the host", name) + di.Log.Warningf("bidder %s supports redirect user sync, but doesn't have a default and must be configured by the host", name) } default: return fmt.Errorf("failed to load bidder info for %s, user sync supported endpoint '%s' is unrecognized", name, endpoint) @@ -367,13 +367,13 @@ func readDefaultRequestFromFile(defReqConfig config.DefReqConfig) []byte { defaultRequestJSON, err := os.ReadFile(defReqConfig.FileSystem.FileName) if err != nil { - glog.Fatalf("error reading default request from file %s: %v", defReqConfig.FileSystem.FileName, err) + di.Log.Fatalf("error reading default request from file %s: %v", defReqConfig.FileSystem.FileName, err) return []byte{} } // validate json is valid if err := jsonutil.UnmarshalValid(defaultRequestJSON, &openrtb2model.BidRequest{}); err != nil { - glog.Fatalf("error parsing default request from file %s: %v", defReqConfig.FileSystem.FileName, err) + di.Log.Fatalf("error parsing default request from file %s: %v", defReqConfig.FileSystem.FileName, err) return []byte{} } diff --git a/server/listener.go b/server/listener.go index 3bc1f2e66fe..5ef16e5322a 100644 --- a/server/listener.go +++ b/server/listener.go @@ -5,7 +5,7 @@ import ( "strings" "time" - "github.com/golang/glog" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/metrics" ) @@ -31,7 +31,7 @@ func (l *monitorableConnection) Close() error { // in the core Go libs: https://github.com/golang/go/issues/4373#issuecomment-347680321 errString := err.Error() if !strings.Contains(errString, "use of closed network connection") { - glog.Errorf("Error closing connection: %s", errString) + di.Log.Errorf("Error closing connection: %s", errString) } l.metrics.RecordConnectionClose(false) } @@ -41,7 +41,7 @@ func (l *monitorableConnection) Close() error { func (ln *monitorableListener) Accept() (net.Conn, error) { tc, err := ln.Listener.Accept() if err != nil { - glog.Errorf("Error accepting connection: %v", err) + di.Log.Errorf("Error accepting connection: %v", err) ln.metrics.RecordConnectionAccept(false) return tc, err } diff --git a/server/prometheus.go b/server/prometheus.go index 98409e6a588..5cf2b7a687b 100644 --- a/server/prometheus.go +++ b/server/prometheus.go @@ -4,7 +4,7 @@ import ( "net/http" "strconv" - "github.com/golang/glog" + "github.com/prebid/prebid-server/v3/di" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/prebid/prebid-server/v3/config" @@ -15,7 +15,7 @@ func newPrometheusServer(cfg *config.Configuration, metrics *metricsconfig.Detai proMetrics := metrics.PrometheusMetrics if proMetrics == nil { - glog.Fatal("Prometheus metrics configured, but a Prometheus metrics engine was not found. Cannot set up a Prometheus listener.") + di.Log.Fatal("Prometheus metrics configured, but a Prometheus metrics engine was not found. Cannot set up a Prometheus listener.") } return &http.Server{ Addr: cfg.Host + ":" + strconv.Itoa(cfg.Metrics.Prometheus.Port), @@ -30,5 +30,5 @@ func newPrometheusServer(cfg *config.Configuration, metrics *metricsconfig.Detai type loggerForPrometheus struct{} func (loggerForPrometheus) Println(v ...interface{}) { - glog.Warningln(v...) + di.Log.Warningln(v...) } diff --git a/server/server.go b/server/server.go index 9461f3f451d..fb55631baa4 100644 --- a/server/server.go +++ b/server/server.go @@ -12,8 +12,8 @@ import ( "time" "github.com/NYTimes/gziphandler" - "github.com/golang/glog" "github.com/prebid/prebid-server/v3/config" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/metrics" metricsconfig "github.com/prebid/prebid-server/v3/metrics/config" ) @@ -36,7 +36,7 @@ func Listen(cfg *config.Configuration, handler http.Handler, adminHandler http.H ) go shutdownAfterSignals(mainServer, stopMain, done) if socketListener, err = newUnixListener(mainServer.Addr, metrics); err != nil { - glog.Errorf("Error listening for Unix-Socket connections on path %s: %v for socket server", mainServer.Addr, err) + di.Log.Errorf("Error listening for Unix-Socket connections on path %s: %v for socket server", mainServer.Addr, err) return } go runServer(mainServer, "UnixSocket", socketListener) @@ -47,7 +47,7 @@ func Listen(cfg *config.Configuration, handler http.Handler, adminHandler http.H ) go shutdownAfterSignals(mainServer, stopMain, done) if mainListener, err = newTCPListener(mainServer.Addr, metrics); err != nil { - glog.Errorf("Error listening for TCP connections on %s: %v for main server", mainServer.Addr, err) + di.Log.Errorf("Error listening for TCP connections on %s: %v for main server", mainServer.Addr, err) return } go runServer(mainServer, "Main", mainListener) @@ -59,7 +59,7 @@ func Listen(cfg *config.Configuration, handler http.Handler, adminHandler http.H var adminListener net.Listener if adminListener, err = newTCPListener(adminServer.Addr, nil); err != nil { - glog.Errorf("Error listening for TCP connections on %s: %v for admin server", adminServer.Addr, err) + di.Log.Errorf("Error listening for TCP connections on %s: %v for admin server", adminServer.Addr, err) return } go runServer(adminServer, "Admin", adminListener) @@ -72,7 +72,7 @@ func Listen(cfg *config.Configuration, handler http.Handler, adminHandler http.H ) go shutdownAfterSignals(prometheusServer, stopPrometheus, done) if prometheusListener, err = newTCPListener(prometheusServer.Addr, nil); err != nil { - glog.Errorf("Error listening for TCP connections on %s: %v for prometheus server", prometheusServer.Addr, err) + di.Log.Errorf("Error listening for TCP connections on %s: %v for prometheus server", prometheusServer.Addr, err) return } @@ -125,17 +125,17 @@ func getCompressionEnabledHandler(h http.Handler, compressionInfo config.Compres func runServer(server *http.Server, name string, listener net.Listener) (err error) { if server == nil { err = fmt.Errorf(">> Server is a nil_ptr.") - glog.Errorf("%s server quit with error: %v", name, err) + di.Log.Errorf("%s server quit with error: %v", name, err) return } else if listener == nil { err = fmt.Errorf(">> Listener is a nil.") - glog.Errorf("%s server quit with error: %v", name, err) + di.Log.Errorf("%s server quit with error: %v", name, err) return } - glog.Infof("%s server starting on: %s", name, server.Addr) + di.Log.Infof("%s server starting on: %s", name, server.Addr) if err = server.Serve(listener); err != nil { - glog.Errorf("%s server quit with error: %v", name, err) + di.Log.Errorf("%s server quit with error: %v", name, err) } return } @@ -150,7 +150,7 @@ func newTCPListener(address string, metrics metrics.MetricsEngine) (net.Listener if casted, ok := ln.(*net.TCPListener); ok { ln = &tcpKeepAliveListener{casted} } else { - glog.Warning("net.Listen(\"tcp\", \"addr\") didn't return a TCPListener as it did in Go 1.9. Things will probably work fine... but this should be investigated.") + di.Log.Warning("net.Listen(\"tcp\", \"addr\") didn't return a TCPListener as it did in Go 1.9. Things will probably work fine... but this should be investigated.") } if metrics != nil { @@ -169,7 +169,7 @@ func newUnixListener(address string, metrics metrics.MetricsEngine) (net.Listene if casted, ok := ln.(*net.UnixListener); ok { ln = &unixListener{casted} } else { - glog.Warning("net.Listen(\"unix\", \"addr\") didn't return an UnixListener.") + di.Log.Warning("net.Listen(\"unix\", \"addr\") didn't return an UnixListener.") } if metrics != nil { @@ -198,9 +198,9 @@ func shutdownAfterSignals(server *http.Server, stopper <-chan os.Signal, done ch defer cancel() var s struct{} - glog.Infof("Stopping %s because of signal: %s", server.Addr, sig.String()) + di.Log.Infof("Stopping %s because of signal: %s", server.Addr, sig.String()) if err := server.Shutdown(ctx); err != nil { - glog.Errorf("Failed to shutdown %s: %v", server.Addr, err) + di.Log.Errorf("Failed to shutdown %s: %v", server.Addr, err) } done <- s } diff --git a/stored_requests/backends/db_fetcher/fetcher.go b/stored_requests/backends/db_fetcher/fetcher.go index 4fcebd3c6d8..931f1ccafa1 100644 --- a/stored_requests/backends/db_fetcher/fetcher.go +++ b/stored_requests/backends/db_fetcher/fetcher.go @@ -6,7 +6,7 @@ import ( "github.com/lib/pq" - "github.com/golang/glog" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/stored_requests" "github.com/prebid/prebid-server/v3/stored_requests/backends/db_provider" ) @@ -18,13 +18,13 @@ func NewFetcher( ) stored_requests.AllFetcher { if provider == nil { - glog.Fatalf("The Database Stored Request Fetcher requires a database connection. Please report this as a bug.") + di.Log.Fatalf("The Database Stored Request Fetcher requires a database connection. Please report this as a bug.") } if queryTemplate == "" { - glog.Fatalf("The Database Stored Request Fetcher requires a queryTemplate. Please report this as a bug.") + di.Log.Fatalf("The Database Stored Request Fetcher requires a queryTemplate. Please report this as a bug.") } if responseQueryTemplate == "" { - glog.Fatalf("The Database Stored Response Fetcher requires a responseQueryTemplate. Please report this as a bug.") + di.Log.Fatalf("The Database Stored Response Fetcher requires a responseQueryTemplate. Please report this as a bug.") } return &dbFetcher{ provider: provider, @@ -62,7 +62,7 @@ func (fetcher *dbFetcher) FetchRequests(ctx context.Context, requestIDs []string rows, err := fetcher.provider.QueryContext(ctx, fetcher.queryTemplate, params...) if err != nil { if err != context.DeadlineExceeded && !isBadInput(err) { - glog.Errorf("Error reading from Stored Request DB: %s", err.Error()) + di.Log.Errorf("Error reading from Stored Request DB: %s", err.Error()) errs := appendErrors("Request", requestIDs, nil, nil) errs = appendErrors("Imp", impIDs, nil, errs) return nil, nil, errs @@ -71,7 +71,7 @@ func (fetcher *dbFetcher) FetchRequests(ctx context.Context, requestIDs []string } defer func() { if err := rows.Close(); err != nil { - glog.Errorf("error closing DB connection: %v", err) + di.Log.Errorf("error closing DB connection: %v", err) } }() @@ -93,7 +93,7 @@ func (fetcher *dbFetcher) FetchRequests(ctx context.Context, requestIDs []string case "imp": storedImpData[id] = data default: - glog.Errorf("Database result set with id=%s has invalid type: %s. This will be ignored.", id, dataType) + di.Log.Errorf("Database result set with id=%s has invalid type: %s. This will be ignored.", id, dataType) } } @@ -127,7 +127,7 @@ func (fetcher *dbFetcher) FetchResponses(ctx context.Context, ids []string) (dat } defer func() { if err := rows.Close(); err != nil { - glog.Errorf("error closing DB connection: %v", err) + di.Log.Errorf("error closing DB connection: %v", err) } }() diff --git a/stored_requests/backends/db_provider/db_provider.go b/stored_requests/backends/db_provider/db_provider.go index 01cd13b7b20..85b8613ba50 100644 --- a/stored_requests/backends/db_provider/db_provider.go +++ b/stored_requests/backends/db_provider/db_provider.go @@ -4,8 +4,8 @@ import ( "context" "database/sql" - "github.com/golang/glog" "github.com/prebid/prebid-server/v3/config" + "github.com/prebid/prebid-server/v3/di" ) type DbProvider interface { @@ -31,15 +31,15 @@ func NewDbProvider(dataType config.DataType, cfg config.DatabaseConnection) DbPr cfg: cfg, } default: - glog.Fatalf("Unsupported database driver %s", cfg.Driver) + di.Log.Fatalf("Unsupported database driver %s", cfg.Driver) return nil } if err := provider.Open(); err != nil { - glog.Fatalf("Failed to open %s database connection: %v", dataType, err) + di.Log.Fatalf("Failed to open %s database connection: %v", dataType, err) } if err := provider.Ping(); err != nil { - glog.Fatalf("Failed to ping %s database: %v", dataType, err) + di.Log.Fatalf("Failed to ping %s database: %v", dataType, err) } return provider diff --git a/stored_requests/backends/http_fetcher/fetcher.go b/stored_requests/backends/http_fetcher/fetcher.go index dc4dd03a1fe..8f5b8af8cd2 100644 --- a/stored_requests/backends/http_fetcher/fetcher.go +++ b/stored_requests/backends/http_fetcher/fetcher.go @@ -13,7 +13,7 @@ import ( "github.com/prebid/prebid-server/v3/util/jsonutil" jsonpatch "gopkg.in/evanphx/json-patch.v4" - "github.com/golang/glog" + "github.com/prebid/prebid-server/v3/di" "golang.org/x/net/context/ctxhttp" ) @@ -55,9 +55,9 @@ func NewFetcher(client *http.Client, endpoint string) *HttpFetcher { // `&request-ids=...&imp-ids=...`. if _, err := url.Parse(endpoint); err != nil { - glog.Fatalf(`Invalid endpoint "%s": %v`, endpoint, err) + di.Log.Fatalf(`Invalid endpoint "%s": %v`, endpoint, err) } - glog.Infof("Making http_fetcher for endpoint %v", endpoint) + di.Log.Infof("Making http_fetcher for endpoint %v", endpoint) urlPrefix := endpoint if strings.Contains(endpoint, "?") { diff --git a/stored_requests/caches/memory/cache.go b/stored_requests/caches/memory/cache.go index c7c9f7ceea8..ce0f33a36de 100644 --- a/stored_requests/caches/memory/cache.go +++ b/stored_requests/caches/memory/cache.go @@ -6,7 +6,7 @@ import ( "sync" "github.com/coocood/freecache" - "github.com/golang/glog" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/stored_requests" ) @@ -19,10 +19,10 @@ import ( func NewCache(size int, ttl int, dataType string) stored_requests.CacheJSON { if ttl > 0 && size <= 0 { // a positive ttl indicates "LRU" cache type, while unlimited size indicates an "unbounded" cache type - glog.Fatalf("unbounded in-memory %s cache with TTL not allowed. Config validation should have caught this. Failing fast because something is buggy.", dataType) + di.Log.Fatalf("unbounded in-memory %s cache with TTL not allowed. Config validation should have caught this. Failing fast because something is buggy.", dataType) } if size > 0 { - glog.Infof("Using a Stored %s in-memory cache. Max size: %d bytes. TTL: %d seconds.", dataType, size, ttl) + di.Log.Infof("Using a Stored %s in-memory cache. Max size: %d bytes. TTL: %d seconds.", dataType, size, ttl) return &cache{ dataType: dataType, cache: &pbsLRUCache{ @@ -31,7 +31,7 @@ func NewCache(size int, ttl int, dataType string) stored_requests.CacheJSON { }, } } else { - glog.Infof("Using an unbounded Stored %s in-memory cache.", dataType) + di.Log.Infof("Using an unbounded Stored %s in-memory cache.", dataType) return &cache{ dataType: dataType, cache: &pbsSyncMap{&sync.Map{}}, diff --git a/stored_requests/caches/memory/maps.go b/stored_requests/caches/memory/maps.go index 9678c4b90e5..89825e8a266 100644 --- a/stored_requests/caches/memory/maps.go +++ b/stored_requests/caches/memory/maps.go @@ -5,7 +5,7 @@ import ( "sync" "github.com/coocood/freecache" - "github.com/golang/glog" + "github.com/prebid/prebid-server/v3/di" ) // This file contains an interface and some wrapper types for various types of "map-like" structures @@ -52,14 +52,14 @@ func (m *pbsLRUCache) Get(id string) (json.RawMessage, bool) { return val, true } if err != freecache.ErrNotFound { - glog.Errorf("unexpected error from freecache: %v", err) + di.Log.Errorf("unexpected error from freecache: %v", err) } return val, false } func (m *pbsLRUCache) Set(id string, value json.RawMessage) { if err := m.Cache.Set([]byte(id), value, m.ttlSeconds); err != nil { - glog.Errorf("error saving value in freecache: %v", err) + di.Log.Errorf("error saving value in freecache: %v", err) } } diff --git a/stored_requests/config/config.go b/stored_requests/config/config.go index 6950c5ebc0c..c9333415c44 100644 --- a/stored_requests/config/config.go +++ b/stored_requests/config/config.go @@ -7,9 +7,9 @@ import ( "github.com/prebid/prebid-server/v3/metrics" - "github.com/golang/glog" "github.com/julienschmidt/httprouter" "github.com/prebid/prebid-server/v3/config" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/stored_requests" "github.com/prebid/prebid-server/v3/stored_requests/backends/db_fetcher" "github.com/prebid/prebid-server/v3/stored_requests/backends/db_provider" @@ -39,7 +39,7 @@ func CreateStoredRequests(cfg *config.StoredRequests, metricsEngine metrics.Metr // Create database connection if given options for one if cfg.Database.ConnectionInfo.Database != "" { if provider == nil { - glog.Infof("Connecting to Database for Stored %s. Driver=%s, DB=%s, host=%s, port=%d, user=%s", + di.Log.Infof("Connecting to Database for Stored %s. Driver=%s, DB=%s, host=%s, port=%d, user=%s", cfg.DataType(), cfg.Database.ConnectionInfo.Driver, cfg.Database.ConnectionInfo.Database, @@ -51,7 +51,7 @@ func CreateStoredRequests(cfg *config.StoredRequests, metricsEngine metrics.Metr // Error out if config is trying to use multiple database connections for different stored requests (not supported yet) if provider.Config() != cfg.Database.ConnectionInfo { - glog.Fatal("Multiple database connection settings found in config, only a single database connection is currently supported.") + di.Log.Fatal("Multiple database connection settings found in config, only a single database connection is currently supported.") } } @@ -76,7 +76,7 @@ func CreateStoredRequests(cfg *config.StoredRequests, metricsEngine metrics.Metr } if err := provider.Close(); err != nil { - glog.Errorf("Error closing DB connection: %v", err) + di.Log.Errorf("Error closing DB connection: %v", err) } } @@ -157,7 +157,7 @@ func newFetcher(cfg *config.StoredRequests, client *http.Client, provider db_pro idList = append(idList, fFetcher) } if cfg.Database.FetcherQueries.QueryTemplate != "" { - glog.Infof("Loading Stored %s data via Database.\nQuery: %s", cfg.DataType(), cfg.Database.FetcherQueries.QueryTemplate) + di.Log.Infof("Loading Stored %s data via Database.\nQuery: %s", cfg.DataType(), cfg.Database.FetcherQueries.QueryTemplate) idList = append(idList, db_fetcher.NewFetcher(provider, cfg.Database.FetcherQueries.QueryTemplate, cfg.Database.FetcherQueries.QueryTemplate)) } else if cfg.Database.CacheInitialization.Query != "" && cfg.Database.PollUpdates.Query != "" { @@ -165,7 +165,7 @@ func newFetcher(cfg *config.StoredRequests, client *http.Client, provider db_pro idList = append(idList, empty_fetcher.EmptyFetcher{}) } if cfg.HTTP.Endpoint != "" { - glog.Infof("Loading Stored %s data via HTTP. endpoint=%s", cfg.DataType(), cfg.HTTP.Endpoint) + di.Log.Infof("Loading Stored %s data via HTTP. endpoint=%s", cfg.DataType(), cfg.HTTP.Endpoint) idList = append(idList, http_fetcher.NewFetcher(client, cfg.HTTP.Endpoint)) } @@ -182,7 +182,7 @@ func newCache(cfg *config.StoredRequests) stored_requests.Cache { } switch { case cfg.InMemoryCache.Type == "none": - glog.Warningf("No %s cache configured. The %s Fetcher backend will be used for all data requests", cfg.DataType(), cfg.DataType()) + di.Log.Warningf("No %s cache configured. The %s Fetcher backend will be used for all data requests", cfg.DataType(), cfg.DataType()) case cfg.DataType() == config.AccountDataType: cache.Accounts = memory.NewCache(cfg.InMemoryCache.Size, cfg.InMemoryCache.TTL, "Accounts") default: @@ -234,10 +234,10 @@ func newHttpEvents(client *http.Client, timeout time.Duration, refreshRate time. } func newFilesystem(dataType config.DataType, configPath string) stored_requests.AllFetcher { - glog.Infof("Loading Stored %s data from filesystem at path %s", dataType, configPath) + di.Log.Infof("Loading Stored %s data from filesystem at path %s", dataType, configPath) fetcher, err := file_fetcher.NewFileFetcher(configPath) if err != nil { - glog.Fatalf("Failed to create a %s FileFetcher: %v", dataType, err) + di.Log.Fatalf("Failed to create a %s FileFetcher: %v", dataType, err) } return fetcher } @@ -247,9 +247,9 @@ func consolidate(dataType config.DataType, fetchers []stored_requests.AllFetcher if len(fetchers) == 0 { switch dataType { case config.RequestDataType: - glog.Warning("No Stored Request support configured. request.imp[i].ext.prebid.storedrequest will be ignored. If you need this, check your app config") + di.Log.Warning("No Stored Request support configured. request.imp[i].ext.prebid.storedrequest will be ignored. If you need this, check your app config") default: - glog.Warningf("No Stored %s support configured. If you need this, check your app config", dataType) + di.Log.Warningf("No Stored %s support configured. If you need this, check your app config", dataType) } return empty_fetcher.EmptyFetcher{} } else if len(fetchers) == 1 { diff --git a/stored_requests/events/database/database.go b/stored_requests/events/database/database.go index 965922b2707..53a7dc25aca 100644 --- a/stored_requests/events/database/database.go +++ b/stored_requests/events/database/database.go @@ -8,8 +8,8 @@ import ( "net" "time" - "github.com/golang/glog" "github.com/prebid/prebid-server/v3/config" + "github.com/prebid/prebid-server/v3/di" "github.com/prebid/prebid-server/v3/metrics" "github.com/prebid/prebid-server/v3/stored_requests/backends/db_provider" "github.com/prebid/prebid-server/v3/stored_requests/events" @@ -49,7 +49,7 @@ type DatabaseEventProducer struct { func NewDatabaseEventProducer(cfg DatabaseEventProducerConfig) (eventProducer *DatabaseEventProducer) { if cfg.Provider == nil { - glog.Fatalf("The Database Stored %s Loader needs a database connection to work.", cfg.RequestType) + di.Log.Fatalf("The Database Stored %s Loader needs a database connection to work.", cfg.RequestType) } return &DatabaseEventProducer{ @@ -88,7 +88,7 @@ func (e *DatabaseEventProducer) fetchAll() (fetchErr error) { e.recordFetchTime(elapsedTime, metrics.FetchAll) if err != nil { - glog.Warningf("Failed to fetch all Stored %s data from the DB: %v", e.cfg.RequestType, err) + di.Log.Warningf("Failed to fetch all Stored %s data from the DB: %v", e.cfg.RequestType, err) if _, ok := err.(net.Error); ok { e.recordError(metrics.StoredDataErrorNetwork) } else { @@ -99,13 +99,13 @@ func (e *DatabaseEventProducer) fetchAll() (fetchErr error) { defer func() { if err := rows.Close(); err != nil { - glog.Warningf("Failed to close the Stored %s DB connection: %v", e.cfg.RequestType, err) + di.Log.Warningf("Failed to close the Stored %s DB connection: %v", e.cfg.RequestType, err) e.recordError(metrics.StoredDataErrorUndefined) fetchErr = err } }() if err := e.sendEvents(rows); err != nil { - glog.Warningf("Failed to load all Stored %s data from the DB: %v", e.cfg.RequestType, err) + di.Log.Warningf("Failed to load all Stored %s data from the DB: %v", e.cfg.RequestType, err) e.recordError(metrics.StoredDataErrorUndefined) return err } @@ -130,7 +130,7 @@ func (e *DatabaseEventProducer) fetchDelta() (fetchErr error) { e.recordFetchTime(elapsedTime, metrics.FetchDelta) if err != nil { - glog.Warningf("Failed to fetch updated Stored %s data from the DB: %v", e.cfg.RequestType, err) + di.Log.Warningf("Failed to fetch updated Stored %s data from the DB: %v", e.cfg.RequestType, err) if _, ok := err.(net.Error); ok { e.recordError(metrics.StoredDataErrorNetwork) } else { @@ -141,13 +141,13 @@ func (e *DatabaseEventProducer) fetchDelta() (fetchErr error) { defer func() { if err := rows.Close(); err != nil { - glog.Warningf("Failed to close the Stored %s DB connection: %v", e.cfg.RequestType, err) + di.Log.Warningf("Failed to close the Stored %s DB connection: %v", e.cfg.RequestType, err) e.recordError(metrics.StoredDataErrorUndefined) fetchErr = err } }() if err := e.sendEvents(rows); err != nil { - glog.Warningf("Failed to load updated Stored %s data from the DB: %v", e.cfg.RequestType, err) + di.Log.Warningf("Failed to load updated Stored %s data from the DB: %v", e.cfg.RequestType, err) e.recordError(metrics.StoredDataErrorUndefined) return err } @@ -213,7 +213,7 @@ func (e *DatabaseEventProducer) sendEvents(rows *sql.Rows) (err error) { storedRespData[id] = data } default: - glog.Warningf("Stored Data with id=%s has invalid type: %s. This will be ignored.", id, dataType) + di.Log.Warningf("Stored Data with id=%s has invalid type: %s. This will be ignored.", id, dataType) } } diff --git a/stored_requests/events/http/http.go b/stored_requests/events/http/http.go index 6ea41a6f848..0b80c82b0ee 100644 --- a/stored_requests/events/http/http.go +++ b/stored_requests/events/http/http.go @@ -15,7 +15,7 @@ import ( "github.com/prebid/prebid-server/v3/stored_requests/events" "github.com/prebid/prebid-server/v3/util/jsonutil" - "github.com/golang/glog" + "github.com/prebid/prebid-server/v3/di" ) // NewHTTPEvents makes an EventProducer which creates events by pinging an external HTTP API @@ -77,7 +77,7 @@ func NewHTTPEvents(client *httpCore.Client, endpoint string, ctxProducer func() saves: make(chan events.Save, 1), invalidations: make(chan events.Invalidation, 1), } - glog.Infof("Loading HTTP cache from GET %s", endpoint) + di.Log.Infof("Loading HTTP cache from GET %s", endpoint) e.fetchAll() go e.refresh(time.Tick(refreshRate)) @@ -117,7 +117,7 @@ func (e *HTTPEvents) refresh(ticker <-chan time.Time) { // Error with url parsing if urlErr != nil { - glog.Errorf("Disabling refresh HTTP cache from GET '%s': %v", e.Endpoint, urlErr) + di.Log.Errorf("Disabling refresh HTTP cache from GET '%s': %v", e.Endpoint, urlErr) return } @@ -133,7 +133,7 @@ func (e *HTTPEvents) refresh(ticker <-chan time.Time) { // Convert to string endpoint := endpointUrl.String() - glog.Infof("Refreshing HTTP cache from GET '%s'", endpoint) + di.Log.Infof("Refreshing HTTP cache from GET '%s'", endpoint) ctx, cancel := e.ctxProducer() resp, err := ctxhttp.Get(ctx, e.client, endpoint) @@ -165,25 +165,25 @@ func (e *HTTPEvents) refresh(ticker <-chan time.Time) { // It returns true if everything was successful, and false if any errors occurred. func (e *HTTPEvents) parse(endpoint string, resp *httpCore.Response, err error) (*responseContract, bool) { if err != nil { - glog.Errorf("Failed call: GET %s for Stored Requests: %v", endpoint, err) + di.Log.Errorf("Failed call: GET %s for Stored Requests: %v", endpoint, err) return nil, false } defer resp.Body.Close() respBytes, err := io.ReadAll(resp.Body) if err != nil { - glog.Errorf("Failed to read body of GET %s for Stored Requests: %v", endpoint, err) + di.Log.Errorf("Failed to read body of GET %s for Stored Requests: %v", endpoint, err) return nil, false } if resp.StatusCode != httpCore.StatusOK { - glog.Errorf("Got %d response from GET %s for Stored Requests. Response body was: %s", resp.StatusCode, endpoint, string(respBytes)) + di.Log.Errorf("Got %d response from GET %s for Stored Requests. Response body was: %s", resp.StatusCode, endpoint, string(respBytes)) return nil, false } var respObj responseContract if err := jsonutil.UnmarshalValid(respBytes, &respObj); err != nil { - glog.Errorf("Failed to unmarshal body of GET %s for Stored Requests: %v", endpoint, err) + di.Log.Errorf("Failed to unmarshal body of GET %s for Stored Requests: %v", endpoint, err) return nil, false }