Skip to content

Commit 031f423

Browse files
committed
feat: improve logging
1 parent 8f16fdb commit 031f423

File tree

1 file changed

+38
-39
lines changed

1 file changed

+38
-39
lines changed

geoblock.go

Lines changed: 38 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,8 @@ func New(ctx context.Context, next http.Handler, config *Config, name string) (h
126126

127127
// output configuration of the middleware instance
128128
if !config.SilentStartUp {
129-
printConfiguration(config, infoLogger)
129+
infoLogger.Printf("%s: Staring middleware", name)
130+
printConfiguration(name, config, infoLogger)
130131
}
131132

132133
// create LRU cache for IP lookup
@@ -136,9 +137,9 @@ func New(ctx context.Context, next http.Handler, config *Config, name string) (h
136137
}
137138

138139
// create custom log target if needed
139-
logFile, err := initializeLogFile(config.LogFilePath, infoLogger)
140+
logFile, err := initializeLogFile(name, config.LogFilePath, infoLogger)
140141
if err != nil {
141-
infoLogger.Printf("Error initializing log file: %v\n", err)
142+
infoLogger.Printf("%s: Error initializing log file: %v\n", name, err)
142143
}
143144

144145
// Set up a goroutine to close the file when the context is done
@@ -147,7 +148,7 @@ func New(ctx context.Context, next http.Handler, config *Config, name string) (h
147148
<-ctx.Done() // Wait for context cancellation
148149
logger.SetOutput(os.Stdout)
149150
logFile.Close()
150-
logger.Printf("Log file closed for middleware: %s\n", name)
151+
logger.Printf("%s; Log file closed for middleware\n", name)
151152
}(infoLogger)
152153
}
153154

@@ -185,7 +186,7 @@ func (a *GeoBlock) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
185186
requestIPAddresses, err := a.collectRemoteIP(req)
186187
if err != nil {
187188
// if one of the ip addresses could not be parsed, return status forbidden
188-
a.infoLogger.Println(err)
189+
a.infoLogger.Printf("%s: %s", a.name, err)
189190
rw.WriteHeader(http.StatusForbidden)
190191
return
191192
}
@@ -287,7 +288,7 @@ func (a *GeoBlock) allowDenyCachedRequestIP(requestIPAddr *net.IP, req *http.Req
287288
}
288289

289290
if a.logAPIRequests {
290-
a.infoLogger.Println("Loaded from database: ", entry)
291+
a.infoLogger.Printf("%s: [%s] loaded from database: %s", a.name, requestIPAddr, entry)
291292
}
292293

293294
// check if existing entry was made more than a month ago, if so update the entry
@@ -330,7 +331,7 @@ func (a *GeoBlock) cachedRequestIP(requestIPAddr *net.IP, req *http.Request) (bo
330331
}
331332

332333
if a.logAPIRequests {
333-
a.infoLogger.Println("Loaded from database: ", entry)
334+
a.infoLogger.Printf("%s: [%s] Loaded from database: %s", a.name, ipAddressString, entry)
334335
}
335336

336337
// check if existing entry was made more than a month ago, if so update the entry
@@ -392,7 +393,7 @@ func (a *GeoBlock) createNewIPEntry(req *http.Request, ipAddressString string) (
392393
a.database.Add(ipAddressString, entry)
393394

394395
if a.logAPIRequests {
395-
a.infoLogger.Println("Added to database: ", entry)
396+
a.infoLogger.Printf("%s: [%s] added to database: %s", a.name, ipAddressString, entry)
396397
}
397398

398399
return entry, nil
@@ -406,16 +407,14 @@ func (a *GeoBlock) getCountryCode(req *http.Request, ipAddressString string) (st
406407
}
407408

408409
if a.logAPIRequests {
409-
a.infoLogger.Print("Failed to read country from HTTP header field [",
410-
a.iPGeolocationHTTPHeaderField,
411-
"], continuing with API lookup.")
410+
a.infoLogger.Printf("%s: Failed to read country from HTTP header field [%s], continuing with API lookup.", a.name, a.iPGeolocationHTTPHeaderField)
412411
}
413412
}
414413

415414
country, err := a.callGeoJS(ipAddressString)
416415
if err != nil {
417416
if !(os.IsTimeout(err) || a.ignoreAPITimeout) {
418-
a.infoLogger.Println(err)
417+
a.infoLogger.Printf("%s: %s", a.name, err)
419418
}
420419
return "", err
421420
}
@@ -463,7 +462,7 @@ func (a *GeoBlock) callGeoJS(ipAddress string) (string, error) {
463462
}
464463

465464
if a.logAPIRequests {
466-
a.infoLogger.Printf("Country [%s] for ip %s fetched from %s", countryCode, ipAddress, apiURI)
465+
a.infoLogger.Printf("%s: Country [%s] for ip %s fetched from %s", a.name, countryCode, ipAddress, apiURI)
467466
}
468467

469468
return countryCode, nil
@@ -584,50 +583,50 @@ func parseAllowedIPAddresses(entries []string, logger *log.Logger) ([]net.IP, []
584583
return allowedIPAddresses, allowedIPRanges
585584
}
586585

587-
func printConfiguration(config *Config, logger *log.Logger) {
588-
logger.Printf("allow local IPs: %t", config.AllowLocalRequests)
589-
logger.Printf("log local requests: %t", config.LogLocalRequests)
590-
logger.Printf("log allowed requests: %t", config.LogAllowedRequests)
591-
logger.Printf("log api requests: %t", config.LogAPIRequests)
586+
func printConfiguration(name string, config *Config, logger *log.Logger) {
587+
logger.Printf("%s: allow local IPs: %t", name, config.AllowLocalRequests)
588+
logger.Printf("%s: log local requests: %t", name, config.LogLocalRequests)
589+
logger.Printf("%s: log allowed requests: %t", name, config.LogAllowedRequests)
590+
logger.Printf("%s: log api requests: %t", name, config.LogAPIRequests)
592591
if len(config.IPGeolocationHTTPHeaderField) == 0 {
593-
logger.Printf("use custom HTTP header field for country lookup: %t", false)
592+
logger.Printf("%s: use custom HTTP header field for country lookup: %t", name, false)
594593
} else {
595-
logger.Printf("use custom HTTP header field for country lookup: %t [%s]", true, config.IPGeolocationHTTPHeaderField)
596-
}
597-
logger.Printf("API uri: %s", config.API)
598-
logger.Printf("API timeout: %d", config.APITimeoutMs)
599-
logger.Printf("ignore API timeout: %t", config.IgnoreAPITimeout)
600-
logger.Printf("cache size: %d", config.CacheSize)
601-
logger.Printf("force monthly update: %t", config.ForceMonthlyUpdate)
602-
logger.Printf("allow unknown countries: %t", config.AllowUnknownCountries)
603-
logger.Printf("unknown country api response: %s", config.UnknownCountryAPIResponse)
604-
logger.Printf("blacklist mode: %t", config.BlackListMode)
605-
logger.Printf("add country header: %t", config.AddCountryHeader)
606-
logger.Printf("countries: %v", config.Countries)
607-
logger.Printf("Denied request status code: %d", config.HTTPStatusCodeDeniedRequest)
608-
logger.Printf("Log file path: %s", config.LogFilePath)
594+
logger.Printf("%s: use custom HTTP header field for country lookup: %t [%s]", name, true, config.IPGeolocationHTTPHeaderField)
595+
}
596+
logger.Printf("%s: API uri: %s", name, config.API)
597+
logger.Printf("%s: API timeout: %d", name, config.APITimeoutMs)
598+
logger.Printf("%s: ignore API timeout: %t", name, config.IgnoreAPITimeout)
599+
logger.Printf("%s: cache size: %d", name, config.CacheSize)
600+
logger.Printf("%s: force monthly update: %t", name, config.ForceMonthlyUpdate)
601+
logger.Printf("%s: allow unknown countries: %t", name, config.AllowUnknownCountries)
602+
logger.Printf("%s: unknown country api response: %s", name, config.UnknownCountryAPIResponse)
603+
logger.Printf("%s: blacklist mode: %t", name, config.BlackListMode)
604+
logger.Printf("%s: add country header: %t", name, config.AddCountryHeader)
605+
logger.Printf("%s: countries: %v", name, config.Countries)
606+
logger.Printf("%s: Denied request status code: %d", name, config.HTTPStatusCodeDeniedRequest)
607+
logger.Printf("%s: Log file path: %s", name, config.LogFilePath)
609608
if len(config.RedirectURLIfDenied) != 0 {
610-
logger.Printf("Redirect URL on denied requests: %s", config.RedirectURLIfDenied)
609+
logger.Printf("%s: Redirect URL on denied requests: %s", name, config.RedirectURLIfDenied)
611610
}
612611
}
613612

614-
func initializeLogFile(logFilePath string, logger *log.Logger) (*os.File, error) {
613+
func initializeLogFile(name string, logFilePath string, logger *log.Logger) (*os.File, error) {
615614
if len(logFilePath) == 0 {
616615
return nil, nil
617616
}
618617

619618
writeable, err := isFolder(logFilePath)
620619
if err != nil {
621-
logger.Println(err)
620+
logger.Printf("%s: %s", name, err)
622621
return nil, err
623622
} else if !writeable {
624-
logger.Println("Specified log folder is not writeable")
625-
return nil, fmt.Errorf("folder is not writeable: %s", logFilePath)
623+
logger.Printf("%s: Specified log folder is not writeable: %s", name, logFilePath)
624+
return nil, fmt.Errorf("%s: folder is not writeable: %s", name, logFilePath)
626625
}
627626

628627
logFile, err := os.OpenFile(logFilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, filePermissions)
629628
if err != nil {
630-
logger.Printf("Failed to open log file: %v\n", err)
629+
logger.Printf("%s: Failed to open log file: %v\n", name, err)
631630
return nil, err
632631
}
633632

0 commit comments

Comments
 (0)