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 装饰器功能以及函数参数使用介绍
Jan 27 Python
python函数参数*args**kwargs用法实例
Dec 04 Python
python通过urllib2爬网页上种子下载示例
Feb 24 Python
Python实现二叉树结构与进行二叉树遍历的方法详解
May 24 Python
Python 多线程Threading初学教程
Aug 22 Python
Python 通配符删除文件的实例
Apr 24 Python
python使用tornado实现简单爬虫
Jul 28 Python
对python dataframe逻辑取值的方法详解
Jan 30 Python
Python3环境安装Scrapy爬虫框架过程及常见错误
Jul 12 Python
python GUI库图形界面开发之PyQt5选项卡控件QTabWidget详细使用方法与实例
Mar 01 Python
python新手学习使用库
Jun 11 Python
Python基于unittest实现测试用例执行
Nov 25 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
收音机的保养
2021/03/01 无线电
PHP 实现代码复用的一个方法 traits新特性
2015/02/22 PHP
php生成唯一数字id的方法汇总
2015/11/18 PHP
laravel自定义分页效果
2017/07/23 PHP
Laravel框架实现多数据库连接操作详解
2019/07/12 PHP
浅谈javascript中createElement事件
2014/12/05 Javascript
js日期范围初始化得到前一个月日期的方法
2015/05/05 Javascript
异步JS框架的作用以及实现方法
2015/10/29 Javascript
JavaScript实现的Tween算法及缓冲特效实例代码
2015/11/03 Javascript
BootStrap table使用方法分析
2016/11/08 Javascript
EasyUI 结合JS导出Excel文件的实现方法
2016/11/10 Javascript
js实现界面向原生界面发消息并跳转功能
2016/11/22 Javascript
vue2中filter()的实现代码
2017/07/09 Javascript
vue-resource调用promise取数据方式详解
2017/07/21 Javascript
vue页面加载闪烁问题的解决方法
2018/03/28 Javascript
详解基于React.js和Node.js的SSR实现方案
2019/03/21 Javascript
详解vue后台系统登录态管理
2019/04/02 Javascript
js实现上传图片并显示图片名称
2019/12/18 Javascript
vue如何搭建多页面多系统应用
2020/06/17 Javascript
[45:16]完美世界DOTA2联赛循环赛 IO vs FTD BO2第二场 11.05
2020/11/06 DOTA
[01:42:49]DOTA2-DPC中国联赛 正赛 iG vs PSG.LGD BO3 第一场 2月26日
2021/03/11 DOTA
详解Python中的序列化与反序列化的使用
2015/06/30 Python
在Python的while循环中使用else以及循环嵌套的用法
2015/10/14 Python
python 解决print数组/矩阵无法完整输出的问题
2020/02/19 Python
浅谈python元素如何去重,去重后如何保持原来元素的顺序不变
2020/02/28 Python
Python基于进程池实现多进程过程解析
2020/04/30 Python
python 实现倒计时功能(gui界面)
2020/11/11 Python
意大利大型购物中心:Oliviero.it
2017/10/19 全球购物
美国机场停车位预订:About Airport Parking
2018/03/26 全球购物
SteelSeries赛睿官网:游戏外设和配件的领先制造商(耳机、键盘、鼠标和鼠标垫)
2018/06/17 全球购物
斐乐美国官方网站:FILA美国
2019/03/01 全球购物
电子专业毕业生自我鉴定
2014/01/22 职场文书
年终晚会主持词
2014/03/25 职场文书
自主招生自荐信格式
2015/03/04 职场文书
2016猴年开门红标语口号
2015/12/26 职场文书
华为HarmonyOS3.0强在哪? 看看鸿蒙3.0这7个小功能
2023/01/09 数码科技