I want to set up my logger once in my Python project and use that throughout the project.
main.py
:
import logging
import test
hostname = {"hostname": socket.gethostname()}
logger = logging.getLogger()
syslog = logging.StreamHandler()
formatter = logging.Formatter("{\"label\":\"%(name)s\", \"level\":\"%(levelname)s\", \"hostname\":\"%(hostname)s\", \"logEntry\": %(message)s, \"timestamp\", \"%(asctime)s\"}")
syslog.setFormatter(formatter)
logger.setLevel(logging.DEBUG)
logger.addHandler(syslog)
logger = logging.LoggerAdapter(logger, hostname)
def entry_point():
logger.debug("entry_point")
test.test_function()
entry_point()
test.py
:
import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
def test_function():
logger.debug("test_function")
This should give me:
entry_point
test_function
... both formatted with the format provider.
However I actually get an error KeyError: 'hostname'
because it would seem the second logger does not know about the hostname
format provider. I've also tried initialising both loggers with __name__
but then I get No handlers could be found for logger "test"
.
Is there a way I can define my logging configuration once and re-use it throughout my application?