Skip to content

Commit 9f9aa5f

Browse files
authored
Improve logging (#92)
- Add instance name to log lines
1 parent 8f16fdb commit 9f9aa5f

File tree

1 file changed

+45
-38
lines changed

1 file changed

+45
-38
lines changed

geoblock.go

Lines changed: 45 additions & 38 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,18 @@ 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.infoLogger.Printf(
411+
"%s: Failed to read country from HTTP header field [%s], continuing with API lookup.",
412+
a.name,
410413
a.iPGeolocationHTTPHeaderField,
411-
"], continuing with API lookup.")
414+
)
412415
}
413416
}
414417

415418
country, err := a.callGeoJS(ipAddressString)
416419
if err != nil {
417420
if !(os.IsTimeout(err) || a.ignoreAPITimeout) {
418-
a.infoLogger.Println(err)
421+
a.infoLogger.Printf("%s: %s", a.name, err)
419422
}
420423
return "", err
421424
}
@@ -463,7 +466,7 @@ func (a *GeoBlock) callGeoJS(ipAddress string) (string, error) {
463466
}
464467

465468
if a.logAPIRequests {
466-
a.infoLogger.Printf("Country [%s] for ip %s fetched from %s", countryCode, ipAddress, apiURI)
469+
a.infoLogger.Printf("%s: Country [%s] for ip %s fetched from %s", a.name, countryCode, ipAddress, apiURI)
467470
}
468471

469472
return countryCode, nil
@@ -584,50 +587,54 @@ func parseAllowedIPAddresses(entries []string, logger *log.Logger) ([]net.IP, []
584587
return allowedIPAddresses, allowedIPRanges
585588
}
586589

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)
590+
func printConfiguration(name string, config *Config, logger *log.Logger) {
591+
logger.Printf("%s: allow local IPs: %t", name, config.AllowLocalRequests)
592+
logger.Printf("%s: log local requests: %t", name, config.LogLocalRequests)
593+
logger.Printf("%s: log allowed requests: %t", name, config.LogAllowedRequests)
594+
logger.Printf("%s: log api requests: %t", name, config.LogAPIRequests)
592595
if len(config.IPGeolocationHTTPHeaderField) == 0 {
593-
logger.Printf("use custom HTTP header field for country lookup: %t", false)
596+
logger.Printf("%s: use custom HTTP header field for country lookup: %t", name, false)
594597
} 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)
598+
logger.Printf("%s: use custom HTTP header field for country lookup: %t [%s]",
599+
name,
600+
true,
601+
config.IPGeolocationHTTPHeaderField,
602+
)
603+
}
604+
logger.Printf("%s: API uri: %s", name, config.API)
605+
logger.Printf("%s: API timeout: %d", name, config.APITimeoutMs)
606+
logger.Printf("%s: ignore API timeout: %t", name, config.IgnoreAPITimeout)
607+
logger.Printf("%s: cache size: %d", name, config.CacheSize)
608+
logger.Printf("%s: force monthly update: %t", name, config.ForceMonthlyUpdate)
609+
logger.Printf("%s: allow unknown countries: %t", name, config.AllowUnknownCountries)
610+
logger.Printf("%s: unknown country api response: %s", name, config.UnknownCountryAPIResponse)
611+
logger.Printf("%s: blacklist mode: %t", name, config.BlackListMode)
612+
logger.Printf("%s: add country header: %t", name, config.AddCountryHeader)
613+
logger.Printf("%s: countries: %v", name, config.Countries)
614+
logger.Printf("%s: Denied request status code: %d", name, config.HTTPStatusCodeDeniedRequest)
615+
logger.Printf("%s: Log file path: %s", name, config.LogFilePath)
609616
if len(config.RedirectURLIfDenied) != 0 {
610-
logger.Printf("Redirect URL on denied requests: %s", config.RedirectURLIfDenied)
617+
logger.Printf("%s: Redirect URL on denied requests: %s", name, config.RedirectURLIfDenied)
611618
}
612619
}
613620

614-
func initializeLogFile(logFilePath string, logger *log.Logger) (*os.File, error) {
621+
func initializeLogFile(name string, logFilePath string, logger *log.Logger) (*os.File, error) {
615622
if len(logFilePath) == 0 {
616623
return nil, nil
617624
}
618625

619626
writeable, err := isFolder(logFilePath)
620627
if err != nil {
621-
logger.Println(err)
628+
logger.Printf("%s: %s", name, err)
622629
return nil, err
623630
} else if !writeable {
624-
logger.Println("Specified log folder is not writeable")
625-
return nil, fmt.Errorf("folder is not writeable: %s", logFilePath)
631+
logger.Printf("%s: Specified log folder is not writeable: %s", name, logFilePath)
632+
return nil, fmt.Errorf("%s: folder is not writeable: %s", name, logFilePath)
626633
}
627634

628635
logFile, err := os.OpenFile(logFilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, filePermissions)
629636
if err != nil {
630-
logger.Printf("Failed to open log file: %v\n", err)
637+
logger.Printf("%s: Failed to open log file: %v\n", name, err)
631638
return nil, err
632639
}
633640

0 commit comments

Comments
 (0)