I'm writing python package/module and would like the logging messages mention what module/class/function they come from. I.e. if I run this code:
import mymodule.utils.worker as worker w = worker.Worker() w.run()
I'd like to logging messages looks like this:
2010-06-07 15:15:29 INFO mymodule.utils.worker.Worker.run <pid/threadid>: Hello from worker
How can I accomplish this?
Thanks.
Here is my solution that came out of this discussion. Thanks to everyone for suggestions.
Usage:
By default it will name logger as ... You can also control the depth by providing parameter:
3 - module.class.method default
2 - module.class
1 - module only
Logger instances are also cached to prevent calculating logger name on each call. I hope someone will enjoy it.
The code:
I tend to use the logging module in my packages/modules like so:
This sets the name of your logger to the name of the module for inclusion in the log message. You can control where the name is by where
%(name)s
is found in the format string. Similarly you can place the pid with%(process)d
and the thread id with%(thread)d
. See the docs for all the options.Formatting example:
Gives me: