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 相关文章推荐
Django imgareaselect手动剪切头像实现方法
May 26 Python
Python实现随机生成有效手机号码及身份证功能示例
Jun 05 Python
深入学习Python中的上下文管理器与else块
Aug 27 Python
python 编码规范整理
May 05 Python
Python基于Logistic回归建模计算某银行在降低贷款拖欠率的数据示例
Jan 23 Python
计算机二级python学习教程(1) 教大家如何学习python
May 16 Python
python Django的web开发实例(入门)
Jul 31 Python
python:解析requests返回的response(json格式)说明
Apr 30 Python
Python字符串格式化f-string多种功能实现
May 07 Python
Python虚拟环境的创建和包下载过程分析
Jun 19 Python
python tkinter的消息框模块(messagebox,simpledialog)
Nov 07 Python
Python+Pillow+Pytesseract实现验证码识别
May 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
ThinkPHP3.2.3框架实现执行原生SQL语句的方法示例
2019/04/03 PHP
js中如何把字符串转化为对象、数组示例代码
2013/07/17 Javascript
基于Vuejs实现购物车功能
2016/08/02 Javascript
jQuery Masonry瀑布流插件使用方法详解
2017/01/18 Javascript
JavaScript手风琴页面制作
2017/05/17 Javascript
利用C/C++编写node.js原生模块的方法教程
2017/07/07 Javascript
详解JavaScript中的坐标和距离
2019/05/27 Javascript
JavaScript生成一个不重复的ID的方法示例
2019/09/16 Javascript
逐行分析鸿蒙系统的 JavaScript 框架(推荐)
2020/09/17 Javascript
vue element-ul实现展开和收起功能的实例代码
2020/11/25 Vue.js
js仿淘宝放大镜效果
2020/12/28 Javascript
[02:43]DOTA2亚洲邀请赛场馆攻略——带你走进东方体育中心
2018/03/19 DOTA
用Python实现一个简单的能够上传下载的HTTP服务器
2015/05/05 Python
Python基于Tkinter实现的记事本实例
2015/06/17 Python
python实现将html表格转换成CSV文件的方法
2015/06/28 Python
Python实现的十进制小数与二进制小数相互转换功能
2017/10/12 Python
用python写扫雷游戏实例代码分享
2018/05/27 Python
set在python里的含义和用法
2019/06/24 Python
python实现文件的分割与合并
2019/08/29 Python
关于Python中定制类的比较运算实例
2019/12/19 Python
python ETL工具 pyetl
2020/06/07 Python
class类在python中获取金融数据的实例方法
2020/12/10 Python
使用Python+Appuim 清理微信的方法
2021/01/26 Python
CSS3中Transition动画属性用法详解
2016/07/04 HTML / CSS
俄罗斯外国汽车和国产汽车配件网上商店:Движком
2020/04/19 全球购物
星空联盟C# .net笔试题
2014/12/05 面试题
幼儿园运动会加油词
2014/02/14 职场文书
追悼会主持词
2014/03/20 职场文书
保证金退回承诺函格式
2015/01/21 职场文书
检讨书范文300字
2015/01/28 职场文书
花木兰观后感
2015/06/10 职场文书
关于保护环境的建议书
2019/06/24 职场文书
导游词之太行山青龙峡
2020/01/14 职场文书
PHP控制循环操作的时间
2021/04/01 PHP
golang 比较浮点数的大小方式
2021/05/02 Golang
php双向队列实例讲解
2021/11/17 PHP