I am using Python logging in this manner:
logger = logging.getLogger("my_logger")
logger.info("Some text.")
I have a bunch of IoT devices all running (making logs). They stream their log data to a database. To differentiate the source, I need to include the source IP address.
Is there a way to get hostname using logging? Is IP Address or hostname tracked/trackable in LogRecords?
In general, what is the best way to add in hostname to a LogRecord?
You can do that by adding a custom log filter and formatter that puts the host name in the log messages.
import logging, platform
class HostnameFilter(logging.Filter):
hostname = platform.node()
def filter(self, record):
record.hostname = HostnameFilter.hostname
return True
handler = logging.StreamHandler()
handler.addFilter(HostnameFilter())
handler.setFormatter(logging.Formatter('%(asctime)s %(hostname)s: %(message)s', datefmt='%b %d %H:%M:%S'))
logger = logging.getLogger()
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.info('Hello, world!')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With