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中的split()函数的使用方法
Apr 07 Python
浅析Python中的序列化存储的方法
Apr 28 Python
详解C++编程中一元运算符的重载
Jan 19 Python
Python中动态检测编码chardet的使用教程
Jul 06 Python
python数据结构学习之实现线性表的顺序
Sep 28 Python
python下载微信公众号相关文章
Feb 26 Python
Python中dict和set的用法讲解
Mar 28 Python
Django 中自定义 Admin 样式与功能的实现方法
Jul 04 Python
pandas取出重复数据的方法
Jul 04 Python
python web框架 django wsgi原理解析
Aug 20 Python
Python的历史与优缺点整理
May 26 Python
python-图片流传输的思路及示例(url转换二维码)
Dec 21 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新建文件的方法实例
2019/09/26 PHP
php实现的数组转xml案例分析
2019/09/28 PHP
关于laravel后台模板laravel-admin select框的使用详解
2019/10/03 PHP
php redis setnx分布式锁简单原理解析
2020/10/23 PHP
jquery 表单进行客户端验证demo
2009/08/24 Javascript
使用js获取地址栏中传递的值
2013/07/02 Javascript
JS实现倒计时和文字滚动的效果实例
2014/10/29 Javascript
javascript Promise简单学习使用方法小结
2016/05/17 Javascript
BootStrap初学者对弹出框和进度条的使用感觉
2016/06/27 Javascript
Angular.js实现注册系统的实例详解
2016/12/18 Javascript
highcharts 在angular中的使用示例代码
2017/09/20 Javascript
JS验证输入的是否是数字及保留几位小数问题
2018/05/09 Javascript
vue中的数据绑定原理的实现
2018/07/02 Javascript
JS实现select选中option触发事件操作示例
2018/07/13 Javascript
js中位运算的运用实例分析
2018/12/11 Javascript
vue 实现购物车总价计算
2019/11/06 Javascript
jQuery实现中奖播报功能(让文本滚动起来) 简单设置数值即可
2020/03/20 jQuery
[35:39]完美世界DOTA2联赛PWL S2 FTD.C vs Rebirth 第二场 11.22
2020/11/24 DOTA
Python简明入门教程
2015/08/04 Python
Python日期的加减等操作的示例
2017/08/15 Python
Python异常处理操作实例详解
2018/05/10 Python
基于DataFrame改变列类型的方法
2018/07/25 Python
django之静态文件 django 2.0 在网页中显示图片的例子
2019/07/28 Python
HTML5 Canvas鼠标与键盘事件demo示例
2013/07/04 HTML / CSS
The Kooples美国官方网站:为情侣提供的法国当代时尚品牌
2019/01/03 全球购物
TCP/IP模型的分界线
2012/12/01 面试题
前台文员的岗位职责
2013/11/14 职场文书
房屋改造计划书
2014/01/10 职场文书
运动会跳远广播稿
2014/02/04 职场文书
村党支部书记承诺书
2014/05/29 职场文书
员工三分钟演讲稿
2014/08/19 职场文书
党员批评与自我批评思想汇报(集锦)
2014/09/14 职场文书
业务员岗位职责范本
2015/04/03 职场文书
走进毛泽东观后感
2015/06/04 职场文书
Python办公自动化之教你用Python批量识别发票并录入到Excel表格中
2021/06/26 Python
Tomcat执行startup.bat出现闪退的原因及解决办法
2022/04/20 Servers