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中splitlines()方法的使用简介
May 20 Python
Python中字符串的常见操作技巧总结
Jul 28 Python
JSON Web Tokens的实现原理
Apr 02 Python
学习Python3 Dlib19.7进行人脸面部识别
Jan 24 Python
Python爬虫小技巧之伪造随机的User-Agent
Sep 13 Python
Python 实现子类获取父类的类成员方法
Jan 11 Python
Django页面数据的缓存与使用的具体方法
Apr 23 Python
Django实现文件上传下载
Oct 06 Python
Pytorch 实现权重初始化
Dec 31 Python
pycharm设置当前工作目录的操作(working directory)
Feb 14 Python
python复合条件下的字典排序
Dec 18 Python
Python+MySQL随机试卷及答案生成程序的示例代码
Feb 01 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开发负载均衡指南
2010/07/17 PHP
日常整理PHP中简单的图形处理(经典)
2015/10/26 PHP
Linux+Nginx+MySQL下配置论坛程序Discuz的基本教程
2015/12/23 PHP
phpQuery采集网页实现代码实例
2020/04/02 PHP
JavaScript中数组对象的那些自带方法介绍
2013/03/12 Javascript
JS操作图片(增,删,改) 例子
2013/04/17 Javascript
JavaScript作用域示例详解
2016/07/07 Javascript
JavaScript实现的select点菜功能示例
2017/01/16 Javascript
在vue.js中使用JSZip实现在前端解压文件的方法
2018/09/05 Javascript
深度了解vue.js中hooks的相关知识
2019/06/14 Javascript
Koa从零搭建到Api实现项目的搭建方法
2019/07/30 Javascript
五句话帮你轻松搞定js原型链
2020/12/09 Javascript
[01:04:31]DOTA2-DPC中国联赛定级赛 iG vs Magma BO3第二场 1月8日
2021/03/11 DOTA
用Python生成器实现微线程编程的教程
2015/04/13 Python
Python中用字符串调用函数或方法示例代码
2017/08/04 Python
详解python如何在django中为用户模型添加自定义权限
2018/10/15 Python
python的range和linspace使用详解
2019/11/27 Python
使用pyinstaller逆向.pyc文件
2019/12/20 Python
Python 抓取数据存储到Redis中的操作
2020/07/16 Python
Python爬虫之Selenium警告框(弹窗)处理
2020/12/04 Python
中国高端家电购物商城:顺电
2018/03/04 全球购物
香港士多网上超级市场:Ztore
2021/01/09 全球购物
医生实习工作总结的自我评价
2013/09/27 职场文书
教育课题研究自我鉴定范文
2013/12/28 职场文书
刊首寄语大全
2014/04/11 职场文书
岗位说明书范文
2014/05/07 职场文书
派出所所长先进事迹
2014/05/19 职场文书
鼓舞士气的口号
2014/06/16 职场文书
党员个人批评与自我批评
2014/10/14 职场文书
倡议书格式及范文
2015/04/29 职场文书
环保建议书作文300字
2015/09/14 职场文书
my.ini优化mysql数据库性能的十个参数(推荐)
2021/05/26 MySQL
用JS创建一个录屏功能
2021/11/11 Javascript
Python OpenCV之常用滤波器使用详解
2022/04/07 Python
python数字图像处理之图像自动阈值分割示例
2022/06/28 Python
Java获取字符串编码格式实现思路
2022/09/23 Java/Android