1.写在前面2.代码1:在控制台输出log日志3.代码2:在文件中写入log日志4. 代码3:在控制台和文件中分别输出log日志
写在前面
log日志一般使用是很方便的,一般使用第二种即可。 详细理解建议仔细阅读第三种写法。 log日志的主要作用有以下两点: 1、错误排查与分析 2、log日志分析,便于编程人员快速了解程序。
代码1:在控制台输出log日志
import logging
logging
.basicConfig
(level
=logging
.WARNING
,
format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
logging
.info
('这是 loggging info message')
logging
.debug
('这是 loggging debug message')
logging
.warning
('这是 loggging a warning message')
logging
.error
('这是 an loggging error message')
logging
.critical
('这是 loggging critical message')
代码2:在文件中写入log日志
import logging
logging
.basicConfig
(level
=logging
.WARNING
,
filename
='./log.txt',
filemode
='w',
format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
logging
.info
('这是 loggging info message')
logging
.debug
('这是 loggging debug message')
logging
.warning
('这是 loggging a warning message')
logging
.error
('这是 an loggging error message')
logging
.critical
('这是 loggging critical message')
当然我们也可以使用sys.stdout() 利用sys.stdout将print行导向到你定义的日志文件中,例如:
import sys
stdout_backup
= sys
.stdout
log_file
= open("message.log", "w")
sys
.stdout
= log_file
print("Now all print info will be written to message.log")
...
log_file
.close
()
sys
.stdout
= stdout_backup
print("Now this will be presented on screen")
代码3:在控制台和文件中分别输出log日志
import logging
logger
= logging
.getLogger
()
logger
.setLevel
(logging
.INFO
)
logfile
= './log.txt'
fh
= logging
.FileHandler
(logfile
, mode
='a')
fh
.setLevel
(logging
.DEBUG
)
ch
= logging
.StreamHandler
()
ch
.setLevel
(logging
.WARNING
)
formatter
= logging
.Formatter
("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh
.setFormatter
(formatter
)
ch
.setFormatter
(formatter
)
logger
.addHandler
(fh
)
logger
.addHandler
(ch
)
logger
.debug
('这是 logger debug message')
logger
.info
('这是 logger info message')
logger
.warning
('这是 logger warning message')
logger
.error
('这是 logger error message')
logger
.critical
('这是 logger critical message')
声明:文章主要参考https://blog.csdn.net/rusi__/article/details/100122350和https://www.cnblogs.com/arkenstone/p/5727883.html,在原博文的基础上添加导航目录,旨在帮助大家以更高效的方式完成开发工作。