Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python logging how to track hostname in logs?

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?

like image 565
Intrastellar Explorer Avatar asked Dec 10 '22 03:12

Intrastellar Explorer


1 Answers

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!')
like image 168
rdas Avatar answered Dec 21 '22 18:12

rdas