Skip to content

Commit bc3ee85

Browse files
committed
Create a custom logging filter to extract the client's IP address
1 parent 805fd4f commit bc3ee85

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

rnacentral/rnacentral/settings.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -203,10 +203,15 @@
203203
"disable_existing_loggers": False,
204204
"formatters": {
205205
"standard": {
206-
"format": "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", # pylint: disable=W0401, C0301
206+
"format": "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s (IP: %(client_ip)s)",
207207
"datefmt": "%d/%b/%Y %H:%M:%S",
208208
}
209209
},
210+
"filters": {
211+
"client_ip": {
212+
"()": "rnacentral.utils.logging_filters.ClientIPFilter",
213+
},
214+
},
210215
"handlers": {
211216
"null": {
212217
"level": "DEBUG",
@@ -216,6 +221,7 @@
216221
"level": "INFO",
217222
"class": "logging.StreamHandler", # writes to stderr
218223
"formatter": "standard",
224+
"filters": ["client_ip"],
219225
},
220226
},
221227
"loggers": {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class ClientIPFilter:
2+
def filter(self, record):
3+
# Attempt to add the client IP to the log record
4+
request = getattr(record, "request", None)
5+
if request:
6+
x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
7+
record.client_ip = (
8+
x_forwarded_for.split(",")[0]
9+
if x_forwarded_for
10+
else request.META.get("REMOTE_ADDR")
11+
)
12+
else:
13+
record.client_ip = "unknown"
14+
return True

0 commit comments

Comments
 (0)