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 ORM框架SQLAlchemy学习笔记之关系映射实例
Jun 10 Python
Python爬虫实现抓取京东店铺信息及下载图片功能示例
Aug 07 Python
浅谈Python中eval的强大与危害
Mar 13 Python
python使用requests.session模拟登录
Aug 09 Python
OpenCV+face++实现实时人脸识别解锁功能
Aug 28 Python
Python大数据之网络爬虫的post请求、get请求区别实例分析
Nov 16 Python
详解Python的三种拷贝方式
Feb 11 Python
小 200 行 Python 代码制作一个换脸程序
May 12 Python
Python连接HDFS实现文件上传下载及Pandas转换文本文件到CSV操作
Jun 06 Python
python rolling regression. 使用 Python 实现滚动回归操作
Jun 08 Python
python3中celery异步框架简单使用+守护进程方式启动
Jan 20 Python
python和Appium的移动端多设备自动化测试框架
Apr 26 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.MVC的模板标签系统(三)
2006/09/05 PHP
那些年一起学习的PHP(二)
2012/03/21 PHP
php中session退出登陆问题
2014/02/27 PHP
PHP判断上传文件类型的解决办法
2015/10/20 PHP
javascript 获取表单file全路径
2009/12/31 Javascript
用AJAX返回HTML片段中的JavaScript脚本
2010/01/04 Javascript
用js小类库获取浏览器的高度和宽度信息
2012/01/15 Javascript
非html5实现js版弹球游戏示例代码
2013/09/22 Javascript
关于js数组去重的问题小结
2014/01/24 Javascript
JavaScript中的lastIndexOf()方法使用详解
2015/06/06 Javascript
Bootstrap框架动态生成Web页面文章内目录的方法
2016/05/12 Javascript
JavaScript+Java实现HTML页面转为PDF文件保存的方法
2016/05/30 Javascript
JavaScript 随机验证码的生成实例代码
2016/09/22 Javascript
JavaScript用构造函数如何获取变量的类型名
2016/12/23 Javascript
用js将long型数据转换成date型或datetime型的实例
2017/07/03 Javascript
使用D3.js制作图表详解
2017/08/13 Javascript
解决Vue 浏览器后退无法触发beforeRouteLeave的问题
2017/12/24 Javascript
微信小程序scroll-view实现字幕滚动
2018/07/14 Javascript
Vue源码探究之状态初始化
2018/11/14 Javascript
JS数组及对象遍历方法代码汇总
2020/06/16 Javascript
使用vue3重构拼图游戏的实现示例
2021/01/25 Vue.js
[03:42]2016国际邀请赛中国区预选赛首日现场玩家采访
2016/06/26 DOTA
python数据结构链表之单向链表(实例讲解)
2017/07/25 Python
Flask数据库迁移简单介绍
2017/10/24 Python
python实现对指定输入的字符串逆序输出的6种方法
2018/04/26 Python
Python如何根据时间序列数据作图
2020/05/12 Python
Django执行源生mysql语句实现过程解析
2020/11/12 Python
html2 canvas生成清晰的图片实现打印功能
2019/09/23 HTML / CSS
保加利亚运动鞋购物网站:SneakerStudio.bg
2020/12/23 全球购物
马智宇结婚主持词
2014/04/01 职场文书
初中成绩单评语
2014/12/29 职场文书
邀请书格式范文
2015/02/02 职场文书
个人自荐书怎么写
2015/03/26 职场文书
创业计划书之牛肉汤快餐店
2019/10/08 职场文书
Netty分布式客户端处理接入事件handle源码解析
2022/03/25 Java/Android
Redis中key的过期删除策略和内存淘汰机制
2022/04/12 Redis