避免`logger = logging.getLogger(__ name __)`

时间:2016-01-11 16:31:38

标签: python logging

我们设置了日志记录,就像django docs告诉我们的那样:

https://docs.djangoproject.com/en/2.1/topics/logging/#using-logging

# import the logging library
import logging

# Get an instance of a logger
logger = logging.getLogger(__name__)

def my_view(request, arg1, arg):
    ...
    if bad_mojo:
        # Log an error message
        logger.error('Something went wrong!')

我想在每个想要记录的Python文件中避免使用这一行:

logger = logging.getLogger(__name__)

我想要简单:

logging.error('Something went wrong!')

但我们希望保留一个功能:我们希望在日志记录输出中看到Python文件名。

到目前为止,我们使用以下格式:

'%(asctime)s %(name)s.%(funcName)s +%(lineno)s: %(levelname)-8s [%(process)d] %(message)s'

示例输出:

2016-01-11 12:12:31 myapp.foo +68: ERROR Something went wrong

如何避免logger = logging.getLogger(__name__)

2 个答案:

答案 0 :(得分:24)

您可以使用logging.basicConfig定义logging提供的默认界面,如下所示:

import logging
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)s.%(funcName)s +%(lineno)s: %(levelname)-8s [%(process)d] %(message)s',
                    )

现在,只要您在应用程序的任何位置执行以下操作,就会使用此定义:

import logging
logging.error(...)

虽然__name__不可用,但可以通过默认LogRecord attributes提供等效(和其他选项),可用于错误字符串格式化 - 包括module,{{1} }和filename。以下是这个实际操作的双脚本演示:

scripta.py

pathname

scriptb.py

import logging
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(module)s %(name)s.%(funcName)s +%(lineno)s: %(levelname)-8s [%(process)d] %(message)s',
                    )

from scriptb import my_view

my_view()

日志记录定义在import logging def my_view(): # Log an error message logging.error('Something went wrong!') 中定义,添加了scripta.py参数。在module中,我们只需导入scriptb.py即可访问此定义的默认值。运行logging时会生成以下输出:

scripta.py

其中显示了发生错误记录的模块(2016-01-14 13:22:24,640 scriptb root.my_view +9: ERROR [14144] Something went wrong! )。

根据this answer,您可以继续使用任何来自Django的每个模块的日志记录配置,关闭Django处理并设置根处理程序,如下所示:

scriptb

答案 1 :(得分:3)

路径名怎么样?来自https://docs.python.org/2/library/logging.html#formatter-objects

<强> /Users/jluc/kds2/wk/explore/test_so_41.py

import logging

#another module, just to have another file...
import test_so_41b

#not so much to use basicConfig as a quick usage of %(pathname)s
logging.basicConfig(level=logging.DEBUG,
                    format='%(pathname)s %(asctime)s %(levelname)s %(message)s',
                    # filename='/tmp/myapp.log',
                    # filemode='w',
                    )

logging.debug('A debug message')
logging.info('Some information')
logging.warning('A shot across the bows')

test_so_41b.dosomething("hey there")

<强> /Users/jluc/kds2/wk/explore/test_so_41b.py

import logging

def dosomething(msg):
    logging.info(msg)

奥黛丽:探索jluc $ python test_so_41.py

输出:

test_so_41.py 2016-01-16 14:46:57,997 DEBUG A debug message
test_so_41.py 2016-01-16 14:46:57,997 INFO Some information
test_so_41.py 2016-01-16 14:46:57,997 WARNING A shot across the bows
/Users/jluc/kds2/wk/explore/test_so_41b.py 2016-01-16 14:46:57,997 INFO hey there