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连接oracle数据库实例
Oct 17 Python
python修改操作系统时间的方法
May 18 Python
在Python的一段程序中如何使用多次事件循环详解
Sep 07 Python
Python实现的购物车功能示例
Feb 11 Python
Python流行ORM框架sqlalchemy安装与使用教程
Jun 04 Python
pandas删除行删除列增加行增加列的实现
Jul 06 Python
python opencv将图片转为灰度图的方法示例
Jul 31 Python
Python基于requests实现模拟上传文件
Apr 21 Python
Python脚本如何在bilibili中查找弹幕发送者
Jun 04 Python
python 基于opencv实现高斯平滑
Dec 18 Python
OpenCV-Python模板匹配人眼的实例
Jun 08 Python
深入浅析python3 依赖倒置原则(示例代码)
Jul 09 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
浅析Dos下运行php.exe,出现没有找到php_mbstring.dll 错误的解决方法
2013/06/29 PHP
php parse_str() 函数的定义和用法
2016/05/23 PHP
HR vs CL BO3 第二场 2.13
2021/03/10 DOTA
jQuery的Ajax时无响应数据的解决方法
2010/05/25 Javascript
不使用中间变量,交换int型的 a, b两个变量的值。
2010/10/29 Javascript
jQuery.buildFragment使用方法及思路分析
2013/01/07 Javascript
浅谈使用MVC模式进行JavaScript程序开发
2015/11/10 Javascript
浅析JavaScript Array和string的转换(推荐)
2016/05/20 Javascript
探索Javascript中this的奥秘
2016/12/11 Javascript
React BootStrap用户体验框架快速上手
2018/03/06 Javascript
vue 父组件给子组件传值子组件给父组件传值的实例代码
2019/04/15 Javascript
Node.JS枚举统计当前文件夹和子目录下所有代码文件行数
2019/08/23 Javascript
解决layer 关闭当前弹窗 关闭遮罩层 input值获取不到的问题
2019/09/25 Javascript
JavaScript实现简单的计算器
2020/01/16 Javascript
JS正则表达式常见函数与用法小结
2020/04/13 Javascript
Python3基础之函数用法
2014/08/13 Python
Python多线程同步Lock、RLock、Semaphore、Event实例
2014/11/21 Python
Python标准库内置函数complex介绍
2014/11/25 Python
使用Python的Tornado框架实现一个一对一聊天的程序
2015/04/25 Python
Python RuntimeError: thread.__init__() not called解决方法
2015/04/28 Python
python 获取一个值在某个区间的指定倍数的值方法
2018/11/12 Python
python pip源配置,pip配置文件存放位置的方法
2019/07/12 Python
PyPDF2读取PDF文件内容保存到本地TXT实例
2020/05/12 Python
CSS3正方体旋转示例代码
2013/08/08 HTML / CSS
巴西手表购物网站:eclock
2019/03/19 全球购物
Optimalprint加拿大:在线打印服务
2020/04/03 全球购物
生物化工专业个人自荐信
2013/09/26 职场文书
实习生的自我鉴定范文欣赏
2013/11/20 职场文书
数控专业大学毕业生职业规划范文
2014/02/06 职场文书
安全月活动总结
2014/05/05 职场文书
社区活动策划方案
2014/08/21 职场文书
向国旗敬礼活动总结
2014/09/27 职场文书
2014年技术工作总结范文
2014/11/20 职场文书
2015年党员创先争优公开承诺书
2015/04/27 职场文书
新农村建设指导员工作总结
2015/08/13 职场文书
Java中的Kotlin 内部类原理
2022/06/16 Java/Android