Advise on using logging.getLogger needed.

Vinay Sajip vinay_sajip at yahoo.co.uk
Fri Oct 7 15:05:10 EDT 2011


On Oct 2, 11:12 pm, "Steven W. Orr" <ste... at syslang.net> wrote:
> I hope I don't sound like I'm ranting :-(

You don't, but neither is it absolutely clear what you're trying to
achieve. BTW the term "root logger" in the logging docs refers to a
logger internal to the logging package, and not to a logger that you
create. For that, it's best to refer to "top level logger for my
application/library".

Supposing you want your top-level logger always to be the name of your
main script, and you want other loggers to live below this logger. In
your main script module, therefore, you do the equivalent of

pname = compute_program_name(sys.argv[0])
logger = logging.getLogger(pname)
# configure logging handlers, filters etc. for your application

In your library modules, if you want them to live under that top-level
logger, then you can do something like

pname = compute_program_name(sys.argv[0])
logger = logging.getLogger('%s.%s' % pname, __name__)

where you can use something other than __name__ for the logger name
suffix, if you want.

> My problem is that I just want the modules that I write, to be able to get the
>  named root logger and still be able to refer to possible sub-loggers.

According to the scheme I describe, if you have two scripts called
"foo" and "bar" which make use of a common module "baz", then events
in the foo module would appear under logger "foo", and events in the
baz module when run from foo would be logged under logger "foo.baz".
When running "bar", events in the bar module would appear under logger
"bar", whereas events in the baz module when run from bar would be
logged under logger "bar.baz". This seems to be what you're asking
for, but I may have misunderstood.

> I am running 2.6, so I don't have access to logging.getChild, but I'm not
> clear that I even want that.

getChild is just a convenience method, you don't need it - you can
just build the logger name as in my example above.

> My modules are used by multiple programs. Does this mean that I should simply
> use __name__ all the time? (That seems inelegant, no?)

Actually __name__ is very elegant, as it is impervious to you moving
your code around and follows the Python package hierarchy. Also, if
you are using third party code (especially from various sources),
using __name__ will make things unambiguous about where exactly events
are being logged from. Third party code typically won't know about
your top-level logger, and __name__ is the one scheme that everything
can agree on - the point about logger names being that they're
supposed to codify "where" in your application events occur, and the
package hierarchy is the canonical representation of source locations
in an application.

Regards,

Vinay Sajip



More information about the Python-list mailing list