Python 实现日志同时输出到屏幕和文件


Posted in Python onFebruary 19, 2020

1. 日志输出到屏幕

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import logging

logging.basicConfig(level=logging.NOTSET, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

logging.debug('This is a debug message.')
logging.info('This is an info message.')
logging.warning('This is a warning message.')
logging.error('This is an error message.')
logging.critical('This is a critical message.')

默认的 level 是 logging.WARNING,低于这个级别的就不输出了。如果需要显示低于 logging.WARNING 级别的内容,可以引入 logging.NOTSET 级别来显示。

DEBUG - 打印全部的日志。详细的信息,通常只出现在诊断问题上。

INFO - 打印 INFO、WARNING、ERROR、CRITICAL 级别的日志。确认一切按预期运行。

WARNING - 打印 WARNING、ERROR、CRITICAL 级别的日志。表明一些问题在不久的将来,这个软件还能按预期工作。

ERROR - 打印 ERROR、CRITICAL 级别的日志。更严重的问题,软件没能执行一些功能。

CRITICAL : 打印 CRITICAL 级别。一个严重的错误,表明程序本身可能无法继续运行。

/usr/bin/python2.7 /home/strong/git_workspace/MonoGRNet/test.py
2019-06-26 16:00:45,990 - root - DEBUG - This is a debug message.
2019-06-26 16:00:45,990 - root - INFO - This is an info message.
2019-06-26 16:00:45,990 - root - WARNING - This is a warning message.
2019-06-26 16:00:45,990 - root - ERROR - This is an error message.
2019-06-26 16:00:45,990 - root - CRITICAL - This is a critical message.

Process finished with exit code 0

2. 日志输出到文件

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import logging
import os.path
import time

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

time_line = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))

print(os.getcwd())
log_path = os.path.dirname(os.getcwd()) + '/'
logfile = log_path + time_line + '.log'

handler = logging.FileHandler(logfile, mode='w')
handler.setLevel(logging.INFO)

formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
handler.setFormatter(formatter)

logger.addHandler(handler)

logger.debug('This is a debug message.')
logger.info('This is an info message.')
logger.warning('This is a warning message.')
logger.error('This is an error message.')
logger.critical('This is a critical message.')
/usr/bin/python2.7 /home/strong/git_workspace/MonoGRNet/test.py
/home/strong/git_workspace/MonoGRNet

Process finished with exit code 0

201906261627.log

2019-06-26 16:27:26,899 - test.py[line:30] - INFO: This is an info message.
2019-06-26 16:27:26,899 - test.py[line:31] - WARNING: This is a warning message.
2019-06-26 16:27:26,899 - test.py[line:32] - ERROR: This is an error message.
2019-06-26 16:27:26,899 - test.py[line:33] - CRITICAL: This is a critical message.

3. 日志同时输出到屏幕和文件

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import logging
import os.path
import time

logger = logging.getLogger(__name__)
logger.setLevel(level=logging.DEBUG)

time_line = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))

print(os.getcwd())
log_path = os.path.dirname(os.getcwd()) + '/'
logfile = log_path + time_line + '.log'

handler = logging.FileHandler(logfile, mode='w')
handler.setLevel(logging.INFO)

formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
handler.setFormatter(formatter)

console = logging.StreamHandler()
console.setLevel(logging.WARNING)

logger.addHandler(handler)
logger.addHandler(console)

logger.debug('This is a debug message.')
logger.info('This is an info message.')
logger.warning('This is a warning message.')
logger.error('This is an error message.')
logger.critical('This is a critical message.')
/usr/bin/python2.7 /home/strong/git_workspace/MonoGRNet/test.py
/home/strong/git_workspace/MonoGRNet
This is a warning message.
This is an error message.
This is a critical message.

Process finished with exit code 0

201906261636.log

2019-06-26 16:36:38,385 - test.py[line:34] - INFO: This is an info message.
2019-06-26 16:36:38,385 - test.py[line:35] - WARNING: This is a warning message.
2019-06-26 16:36:38,385 - test.py[line:36] - ERROR: This is an error message.
2019-06-26 16:36:38,385 - test.py[line:37] - CRITICAL: This is a critical message.

以上这篇Python 实现日志同时输出到屏幕和文件就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python编程之string相关操作实例详解
Jul 22 Python
python-docx修改已存在的Word文档的表格的字体格式方法
May 08 Python
Python实现的查询mysql数据库并通过邮件发送信息功能
May 17 Python
基于python实现简单日历
Jul 28 Python
浅谈Django的缓存机制
Aug 23 Python
python高效过滤出文件夹下指定文件名结尾的文件实例
Oct 21 Python
Python绘制堆叠柱状图的实例
Jul 09 Python
python实现FTP文件传输的方法(服务器端和客户端)
Mar 20 Python
浅谈python量化 双均线策略(金叉死叉)
Jun 03 Python
关于tf.matmul() 和tf.multiply() 的区别说明
Jun 18 Python
安装pyinstaller遇到的各种问题(小结)
Nov 20 Python
Python基于Tkinter开发一个爬取B站直播弹幕的工具
May 06 Python
python 控制台单行刷新,多行刷新实例
Feb 19 #Python
python tqdm 实现滚动条不上下滚动代码(保持一行内滚动)
Feb 19 #Python
python 解决tqdm模块不能单行显示的问题
Feb 19 #Python
python 实现在shell窗口中编写print不向屏幕输出
Feb 19 #Python
Python换行与不换行的输出实例
Feb 19 #Python
Python print不能立即打印的解决方式
Feb 19 #Python
python 解决print数组/矩阵无法完整输出的问题
Feb 19 #Python
You might like
PHP调用三种数据库的方法(2)
2006/10/09 PHP
Apache PHP MySql安装配置图文教程
2016/08/27 PHP
layui框架实现文件上传及TP3.2.3(thinkPHP)对上传文件进行后台处理操作示例
2018/05/12 PHP
Yii2.0框架实现带分页的多条件搜索功能示例
2019/02/20 PHP
不用写JS也能使用EXTJS视频演示
2008/12/29 Javascript
jQuery 性能优化指南(2)
2009/05/21 Javascript
JavaScript 编写匿名函数的几种方法
2010/02/21 Javascript
jquery 触发a链接点击事件解决方案
2013/05/02 Javascript
Bootstrap每天必学之模态框(Modal)插件
2016/04/26 Javascript
Jquery on方法绑定事件后执行多次的解决方法
2016/06/02 Javascript
JS常用函数和常用技巧小结
2016/10/15 Javascript
一个极为简单的requirejs实现方法
2016/10/20 Javascript
基于slideout.js实现移动端侧边栏滑动特效
2016/11/28 Javascript
jquery做个日期选择适用于手机端示例
2017/01/10 Javascript
vue如何实现observer和watcher源码解析
2017/03/09 Javascript
vue中实现滚动加载更多的示例
2017/11/08 Javascript
详谈DOM简介及节点、属性、查找节点的方法
2017/11/16 Javascript
Layui 设置select下拉框自动选中某项的方法
2018/08/14 Javascript
解决layui-open关闭自身窗口的问题
2019/09/10 Javascript
[02:11]2014DOTA2 TI专访VG战队Fenrir:队伍气氛良好
2014/07/11 DOTA
Python命令行参数解析模块optparse使用实例
2015/04/13 Python
Python实现读取txt文件并转换为excel的方法示例
2018/05/17 Python
python实现逐个读取txt字符并修改
2018/12/24 Python
python实现Flappy Bird源码
2018/12/24 Python
详解python爬虫系列之初识爬虫
2019/04/06 Python
解决pycharm运行程序出现卡住scanning files to index索引的问题
2019/06/27 Python
小学毕业感言50字
2014/02/16 职场文书
行政部工作岗位职责范本
2014/03/05 职场文书
文秘档案管理岗位职责
2014/03/06 职场文书
党员教师一句话承诺
2014/05/30 职场文书
党员对照检查剖析材料
2014/10/13 职场文书
推广普通话的宣传语
2015/07/13 职场文书
《爬天都峰》教学反思
2016/02/23 职场文书
《鲸》教学反思
2016/02/23 职场文书
2016年庆祝六一儿童节活动总结
2016/04/06 职场文书
入党心得体会
2019/06/20 职场文书