How can I log the package name in Python?
I don't know how to get a "package name" like Java does by default, but to add the filename (which gives you just as much context), use %(pathname)s
in your format string:
'format': '[%(levelname)s] %(message)s [%(pathname)s %(funcName)s %(lineno)d]'
See the documentation here: https://docs.python.org/2/library/logging.html#logrecord-attributes
I would recommend generating your package's logger with logging.getLogger(__name__.split('.')[0])
, configure it with a formatter that includes the name
parameter and then generate your module's logger with logging.getLogger(__name__)
.
For example:
import logging
formatter = logging.Formatter('%(name)s - %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
handler.setLevel(logging.INFO)
package_logger = logging.getLogger(__name__.split('.')[0])
package_logger.setLevel(logging.INFO)
package_logger.addHandler(handler)
logger = logging.getLogger(__name__)
logger.info('message')
For a module module.py
located inside of a package named package
, the logger.info()
call should generate the following message to STDERR
:
package.module - message
Inside of other modules within the same package, you can simply setup your logger as follows to get similar functionality to work in it:
import logging
logger = logging.getLogger(__name__)
logger.info('another message')
For a module another.py
inside of the package package
, called from the module.py
module of the same package, this should generate the following text to STDERR
:
package.another - another message