Python 标准日志记录

标签 python logging

我喜欢使用 python 日志记录模块,因为它使我的应用程序标准化并且更容易获得指标。我面临的问题是,对于每个应用程序(或 file.py),我一直将它放在我的代码之上。

logger = logging.getLogger(__name__)
if not os.path.exists('log'):
    os.makedirs('log')

logName=time.strftime("%Y%m%d.log")    
hdlr = logging.FileHandler('log/%s'%(logName))

logger.setLevel(logging.INFO)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(funcName)s %(levelname)s - %(message)s')

ch.setFormatter(formatter)
hdlr.setFormatter(formatter)

logger.addHandler(ch)
logger.addHandler(hdlr)

这是乏味和重复的。有一个更好的方法吗? 人们如何登录具有多个模块的大型应用程序?

最佳答案

看看logging.basicConfig() .

如果您将 basicConfig() 包装在一个函数中,那么您只需导入您的函数并传递特定的参数(即日志文件名格式级别等)。

这将有助于压缩代码并使其更具可扩展性。

例如——

import logging

def test_logging(filename, format):
    logging.basicConfig(filename=filename, format=format, level=logging.DEBUG)

    # test
    logging.info('Info test...')
    logging.debug('Debug test...')

然后只需将 test_logging() 函数导入其他程序即可。

希望这对您有所帮助。

关于Python 标准日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32890107/

相关文章:

java - 如何在静态方法中拥有log.info

ios - iPhone一夜之间断开了USB连接,没有系统日志

c# - NLog 不写入事件日志 .NET Core 2.1

ruby - 使用 Ruby 按时间戳对文本文件中的行进行排序

python - 应用引擎,python : Is there a memory leak in taskqueue. 添加()?

python - 在 PySpark 中将 Spark DataFrame 从行转换为列,并将其附加到另一个 DataFrame

python - 使用Pycharm调试django meet错误

java - 未创建 Log4j 文件 : logging from the application running on WAS6. 1

python - SocketServer 导致错误 10053

python - 将 Python 中的打印列表转换回实际列表的最佳方法是什么