博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 日志打印模块,输出时间、文件名、行号信息等
阅读量:4200 次
发布时间:2019-05-26

本文共 2004 字,大约阅读时间需要 6 分钟。

python 日志打印模块,输出时间、文件名、行号等信息

通过logging模块来控制日志的输出,相比print直接格式化输出,更加的方便;可以添加更多的日志信息,比如时间、行号、文件信息统一输出;可以通过 setLevel 来统一控制日志的开启与关闭。

下面是参考代码:

#!/usr/bin/env python# -*-coding:UTF-8-*-import logginglogging.basicConfig(format='%(asctime)s.%(msecs)03d [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s',                    datefmt='## %Y-%m-%d %H:%M:%S')logging.getLogger().setLevel(logging.DEBUG)logger = logging.getLogger()logger.debug("This is a debug log")logger.info("This is an info log")logger.critical("This is critical")logger.error("An error occurred\n")

输出结果:

29-02-2020:12:41:17,935 DEBUG    [log.py:11] This is a debug log29-02-2020:12:41:17,935 INFO     [log.py:12] This is an info log29-02-2020:12:41:17,935 CRITICAL [log.py:13] This is critical29-02-2020:12:41:17,935 ERROR    [log.py:14] An error occurred

如果在项目中需要设置多个不同的日志输出器,可以参考下面的代码:

#!/usr/bin/env python# -*-coding:UTF-8-*-import logging# 设置输出格式logging.basicConfig(format='%(asctime)s.%(msecs)03d [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s',                    datefmt='## %Y-%m-%d %H:%M:%S')# 设置日志打印级别logging.getLogger("test").setLevel(logging.DEBUG)# 设置日志输出器的名字,可以在项目中配置多个不同的日志输出器logger = logging.getLogger("test")logging.getLogger("info").setLevel(logging.INFO)logger2 = logging.getLogger("info")logger.debug("This is a debug log")logger.info("This is an info log")logger.critical("This is critical")logger.error("An error occurred\n")logger2.debug("This is a debug log")logger2.info("This is an info log")logger2.critical("This is critical")logger2.error("An error occurred")

输出结果:

29-02-2020:12:36:30,272 DEBUG    [log.py:17] This is a debug log29-02-2020:12:36:30,272 INFO     [log.py:18] This is an info log29-02-2020:12:36:30,272 CRITICAL [log.py:19] This is critical29-02-2020:12:36:30,272 ERROR    [log.py:20] An error occurred29-02-2020:12:36:30,273 INFO     [log.py:23] This is an info log29-02-2020:12:36:30,273 CRITICAL [log.py:24] This is critical29-02-2020:12:36:30,273 ERROR    [log.py:25] An error occurred

转载地址:http://wqfli.baihongyu.com/

你可能感兴趣的文章
android中使用TextView来显示某个网址的内容,使用<ScrollView>来生成下拉列表框
查看>>
andorid里关于wifi的分析
查看>>
Spring MVC 教程,快速入门,深入分析
查看>>
Ubuntu Navicat for MySQL安装以及破解方案
查看>>
在C++中如何实现模板函数的外部调用
查看>>
HTML5学习之——HTML 5 应用程序缓存
查看>>
HTML5学习之——HTML 5 服务器发送事件
查看>>
hbase shell出现ERROR: org.apache.hadoop.hbase.ipc.ServerNotRunningYetException
查看>>
解决Rhythmbox乱码
查看>>
豆瓣爱问共享资料插件发布啦
查看>>
kermit的安装和配置
查看>>
linux中cat命令使用详解
查看>>
java中的异常机制
查看>>
商务智能-基本方法-数据钻取
查看>>
openstack-instance-high-availability-Evacuate
查看>>
evacuate-instance-automatically
查看>>
pycharm常用设置(keymap设置及eclipse常用快捷键总结)
查看>>
关于在openstack的环境变量.bashrc自定自己简化命令
查看>>
Openstack Heat Project介绍(转)
查看>>
How to Perform an Upgrade from Icehouse to Juno(ice升级到juno)
查看>>