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下函数参数的传递(参数带星号的说明)
Sep 19 Python
python获取网页状态码示例
Mar 30 Python
Python字符串处理实例详解
May 18 Python
速记Python布尔值
Nov 09 Python
Python抓取框架Scrapy爬虫入门:页面提取
Dec 01 Python
Python反射的用法实例分析
Feb 11 Python
python中从str中提取元素到list以及将list转换为str的方法
Jun 26 Python
对python 调用类属性的方法详解
Jul 02 Python
使用Python自动生成HTML的方法示例
Aug 06 Python
如何使用python的ctypes调用医保中心的dll动态库下载医保中心的账单
May 24 Python
python 识别登录验证码图片功能的实现代码(完整代码)
Jul 03 Python
端午节将至,用Python爬取粽子数据并可视化,看看网友喜欢哪种粽子吧!
Jun 11 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 zend 相对路径问题
2009/01/12 PHP
PHP JSON格式数据交互实例代码详解
2011/01/13 PHP
php中XMLHttpRequest(Ajax)不能设置自定义的Referer的解决方法
2011/11/26 PHP
PHP数据库链接类(PDO+Access)实例分享
2013/12/05 PHP
codeigniter上传图片不能正确识别图片类型问题解决方法
2014/07/25 PHP
javascript 关于# 和 void的区别分析
2009/10/26 Javascript
Jquery Select操作方法集合脚本之家特别版
2010/05/17 Javascript
解决js正则匹配换行问题实现代码
2012/12/10 Javascript
JavaScript函数详解
2014/11/17 Javascript
js实现同一页面可多次调用的图片幻灯切换效果
2015/02/28 Javascript
JS实现浏览器状态栏文字从右向左弹出效果代码
2015/10/27 Javascript
基于JavaScript实现网页倒计时自动跳转代码
2015/12/28 Javascript
浅析JavaScript函数的调用模式
2016/08/10 Javascript
用原生js做单页应用
2017/01/17 Javascript
JavaScript ES6中export、import与export default的用法和区别
2017/03/14 Javascript
vue2.0实战之使用vue-cli搭建项目(2)
2017/03/27 Javascript
详解关于element级联选择器数据回显问题
2019/02/20 Javascript
Vuex的actions属性的具体使用
2019/04/14 Javascript
Django+Vue实现WebSocket连接的示例代码
2019/05/28 Javascript
Vue组件间通信 Vuex的用法解析
2019/08/05 Javascript
JavaScript实现简单计算器功能
2019/12/19 Javascript
python爬虫之百度API调用方法
2017/06/11 Python
python微信跳一跳系列之自动计算跳一跳距离
2018/02/26 Python
python2.7实现邮件发送功能
2018/12/12 Python
django基于存储在前端的token用户认证解析
2019/08/06 Python
使用Python刷淘宝喵币(低阶入门版)
2019/10/30 Python
python 实现矩阵填充0的例子
2019/11/29 Python
护理专业应届毕业生推荐信
2013/11/15 职场文书
新郎父亲婚宴答谢词
2014/01/11 职场文书
基层干部十八大感言
2014/01/19 职场文书
五好党支部事迹材料
2014/02/06 职场文书
《苏珊的帽子》教学反思
2014/04/07 职场文书
专题组织生活会方案
2014/06/15 职场文书
房地产置业顾问岗位职责
2015/04/11 职场文书
SQL基础查询和LINQ集成化查询
2022/01/18 MySQL
SQL Server数据库备份和恢复数据库的全过程
2022/06/14 SQL Server