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 相关文章推荐
利用打码兔和超人打码自封装的打码类分享
Mar 16 Python
python使用sorted函数对列表进行排序的方法
Apr 04 Python
Python中文件操作简明介绍
Apr 13 Python
python实现bucket排序算法实例分析
May 04 Python
对python中词典的values值的修改或新增KEY详解
Jan 20 Python
python频繁写入文件时提速的方法
Jun 26 Python
Python 获取numpy.array索引值的实例
Dec 06 Python
Python + selenium + crontab实现每日定时自动打卡功能
Mar 31 Python
python中rc1什么意思
Jun 19 Python
Python 数据的累加与统计的示例代码
Aug 03 Python
python自动提取文本中的时间(包含中文日期)
Aug 31 Python
Python sklearn分类决策树方法详解
Sep 23 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查询MySQL大量数据的时候内存占用分析
2011/07/22 PHP
PHP实现连接设备、通讯和发送命令的方法
2015/10/13 PHP
完美解决在ThinkPHP控制器中命名空间的问题
2017/05/05 PHP
javascript 火狐(firefox)不显示本地图片问题解决
2008/07/05 Javascript
Javascript学习笔记之 函数篇(一) : 函数声明和函数表达式
2014/06/24 Javascript
JS实现点击按钮自动增加一个单元格的方法
2015/03/09 Javascript
JavaScript实现斗地主游戏的思路
2016/02/29 Javascript
使用BootStrap实现标签切换原理解析
2017/03/14 Javascript
nodejs中art-template模板语法的引入及冲突解决方案
2017/11/07 NodeJs
js与jQuery实现的用户注册协议倒计时功能实例【三种方法】
2017/11/09 jQuery
bootstrap实现二级下拉菜单效果
2017/11/23 Javascript
深入剖析Express cookie-parser中间件实现示例
2018/02/01 Javascript
vue2.0 axios跨域并渲染的问题解决方法
2018/03/08 Javascript
Vue组件中prop属性使用说明实例代码详解
2018/05/31 Javascript
vue实现多组关键词对应高亮显示功能
2019/07/25 Javascript
[02:34]DOTA2亚洲邀请赛 BG战队出场宣传片
2015/03/09 DOTA
[01:21]DOTA2 新英雄 森海飞霞
2020/12/18 DOTA
python随机生成指定长度密码的方法
2015/04/04 Python
python读取视频流提取视频帧的两种方法
2020/10/22 Python
基于python指定包的安装路径方法
2018/10/27 Python
pyqt5移动鼠标显示坐标的方法
2019/06/21 Python
Python双链表原理与实现方法详解
2020/02/22 Python
利用python实现凯撒密码加解密功能
2020/03/31 Python
python3.6中anaconda安装sklearn踩坑实录
2020/07/28 Python
Python析构函数__del__定义原理解析
2020/11/20 Python
CSS3制作炫酷的自定义发光文字
2016/03/28 HTML / CSS
DVF官方网站:美国时装界尊尚品牌
2017/08/29 全球购物
DOM和JQuery对象有什么区别
2016/11/11 面试题
物流管理专业求职信
2014/05/29 职场文书
森林防火标语
2014/06/23 职场文书
党的群众路线教育实践活动总结材料
2014/10/30 职场文书
早会开场白台词大全
2015/06/01 职场文书
卡特教练观后感
2015/06/08 职场文书
上帝为你开了一扇窗之Tkinter常用函数详解
2021/06/02 Python
JavaScript实现两个数组的交集
2022/03/25 Javascript
mysql5.5中文乱码问题解决的有用方法
2022/05/30 MySQL