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 相关文章推荐
浅谈Pandas:Series和DataFrame间的算术元素
Dec 22 Python
Python中Numpy mat的使用详解
May 24 Python
利用python读取YUV文件 转RGB 8bit/10bit通用
Dec 09 Python
Python如何基于selenium实现自动登录博客园
Dec 16 Python
pytorch查看torch.Tensor和model是否在CUDA上的实例
Jan 03 Python
利用jupyter网页版本进行python函数查询方式
Apr 14 Python
在spyder IPython console中,运行代码加入参数的实例
Apr 20 Python
python如何处理程序无法打开
Jun 16 Python
简述python Scrapy框架
Aug 17 Python
python opencv pytesseract 验证码识别的实现
Aug 28 Python
python基本算法之实现归并排序(Merge sort)
Sep 01 Python
Python opencv缺陷检测的实现及问题解决
Apr 24 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
星际争霸兵种名称对照表
2020/03/04 星际争霸
php购物网站支付paypal使用方法
2010/11/28 PHP
php计划任务之验证是否有多个进程调用同一个job的方法
2015/12/07 PHP
win7 wamp 64位 php环境开启curl服务遇到的问题及解决方法
2018/09/16 PHP
javascript preload&lazy load
2010/05/13 Javascript
jquery三个关闭弹出层的小示例
2013/11/05 Javascript
js父页面与子页面不同时显示的方法
2014/10/16 Javascript
js游戏人物上下左右跑步效果代码分享
2015/08/28 Javascript
javascript实现很浪漫的气泡冒出特效
2020/09/05 Javascript
jQuery 中ajax异步调用的四种方式
2016/06/28 Javascript
AngularJS中指令的四种基本形式实例分析
2016/11/22 Javascript
Angular排序实例详解
2017/06/28 Javascript
jQuery实现通过方向键控制div块上下左右移动的方法【测试可用】
2018/04/26 jQuery
vue里面v-bind和Props 利用props绑定动态数据的方法
2018/08/27 Javascript
Vue弹出菜单功能的实现代码
2018/09/12 Javascript
Nodejs 识别图片类型的方法
2019/08/15 NodeJs
在Webpack中用url-loader处理图片和字体的问题
2020/04/28 Javascript
通过实例了解JS执行上下文运行原理
2020/06/17 Javascript
vue中defineProperty和Proxy的区别详解
2020/11/30 Vue.js
Python 列表list使用介绍
2014/11/30 Python
用Python制作检测Linux运行信息的工具的教程
2015/04/01 Python
Python fileinput模块使用实例
2015/06/03 Python
详解Python 调用C# dll库最简方法
2019/06/20 Python
如何使用Python破解ZIP或RAR压缩文件密码
2020/01/09 Python
pytorch构建多模型实例
2020/01/15 Python
tensorflow查看ckpt各节点名称实例
2020/01/21 Python
django2.2 和 PyMySQL版本兼容问题
2020/02/17 Python
django中的数据库迁移的实现
2020/03/16 Python
HTML5 Canvas玩转酷炫大波浪进度图效果实例(附demo)
2016/12/14 HTML / CSS
Europcar德国:全球汽车租赁领域的领导者
2018/08/15 全球购物
财务总监管理岗位职责
2014/03/08 职场文书
优乐美广告词
2014/03/14 职场文书
个人债务授权委托书
2014/10/17 职场文书
幼儿园家长心得体会
2016/01/21 职场文书
浅谈由position属性引申的css进阶讨论
2021/05/25 HTML / CSS
详解Python requests模块
2021/06/21 Python