Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add NetworkContextFilter #8

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ Installation
The pacakage on PyPI is named ``humiologging``, same as the package name.
Install with for instance ``pip install humiologging``.

Filters
-------

``humiologging.filters.NetworkContextFilter``
Optional filter that adds public and local ip to the log-record. Use with
any handler. Mostly useful for debugging.

Formatters
----------

Expand Down
12 changes: 12 additions & 0 deletions src/humiologging/filters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import logging
from .utils import find_my_local_ip, find_my_public_ip


class NetworkContextFilter(logging.Filter):
public_ip = find_my_public_ip()
local_ip = find_my_local_ip()

def filter(self, record):
record.public_ip = self.public_ip
record.local_ip = self.local_ip
return True
16 changes: 16 additions & 0 deletions src/humiologging/utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from datetime import datetime, timezone
import requests
import socket


Expand Down Expand Up @@ -42,3 +43,18 @@ def make_safe_for_json(recorddict):
if not isinstance(value, PRIMITIVE_TYPES):
recorddict[key] = repr(value)
return recorddict


def find_my_public_ip():
response = requests.get("https://httpbin.org/ip")
if response.status_code == 200:
server_ip = response.json()['origin']
return server_ip
return None


def find_my_local_ip():
try:
return socket.gethostbyname(socket.gethostname())
except socket.error:
return None