Avoid `logger=logging.getLogger(__name__)` without

2019-09-23 06:52发布

I am lazy and want to avoid this line in every python file which uses logging:

logger = logging.getLogger(__name__)

In january I asked how this could be done, and found an answer: Avoid `logger=logging.getLogger(__name__)`

Unfortunately the answer there has the drawback, that you loose the ability to filter.

I really want to avoid this useless and redundant line.

Example:

import logging

def my_method(foo):
    logging.info() 

Unfortunately I think it is impossible do logger = logging.getLogger(__name__) implicitly if logging.info() gets called for the first time in this file.

Is there anybody out there who knows how to do impossible stuff?

Update

I like Don't Repeat Yourself. If most files contain the same line at the top, I think this is a repetition. It looks like WET. The python interpreter in my head needs to skip this line every time I look there. My subjective feeling: this line is useless bloat. The line should be the implicit default.

2条回答
霸刀☆藐视天下
2楼-- · 2019-09-23 07:35

Think well if you really want to do this.

Create a Module e.g. magiclog.py like this:

import logging
import inspect

def L():
    # FIXME: catch indexing errors
    callerframe = inspect.stack()[1][0]
    name = callerframe.f_globals["__name__"]
    # avoid cyclic ref, see https://docs.python.org/2/library/inspect.html#the-interpreter-stack
    del callerframe
    return logging.getLogger(name)

Then you can do:

from magiclog import L
L().info("it works!")
查看更多
Viruses.
3楼-- · 2019-09-23 07:38

I am lazy and want to avoid this line in every python file which uses logging:

logger = logging.getLogger(__name__)

Well, it's the recommended way:

A good convention to use when naming loggers is to use a module-level logger, in each module which uses logging, named as follows:

logger = logging.getLogger(__name__)

This means that logger names track the package/module hierarchy, and it’s intuitively obvious where events are logged just from the logger name.

That's a quote from the official howto.

I like Don't Repeat Yourself. If most files contain the same line at the top, I think this is a repetition. It looks like WET. The python interpreter in my head needs to skip this line every time I look there. My subjective feeling: this line is useless bloat. The line should be the implicit default.

It follows "Explicit is better than implicit". Anyway you can easily change a python template in many IDEs to always include this line or make a new template file.

查看更多
登录 后发表回答