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中的文件I/O操作
May 24 Python
Python实现计算最小编辑距离
Mar 17 Python
python之pandas用法大全
Mar 13 Python
Python字符串、整数、和浮点型数相互转换实例
Aug 04 Python
Python 字符串换行的多种方式
Sep 06 Python
Python中分支语句与循环语句实例详解
Sep 13 Python
python爬虫之快速对js内容进行破解
Jul 09 Python
numpy创建单位矩阵和对角矩阵的实例
Nov 29 Python
Python利用PyExecJS库执行JS函数的案例分析
Dec 18 Python
Django实现whoosh搜索引擎使用jieba分词
Apr 08 Python
在jupyter notebook 添加 conda 环境的操作详解
Apr 10 Python
pytorch中的torch.nn.Conv2d()函数图文详解
Feb 28 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实现的二分查找算法实例分析
2017/12/19 PHP
JS中==与===操作符的比较
2009/03/21 Javascript
Jquery 基础学习笔记之文档处理
2009/05/29 Javascript
intro.js 页面引导简单用法 分享
2013/08/06 Javascript
jQuery中:header选择器用法实例
2014/12/29 Javascript
jQuery Validate表单验证入门学习
2015/12/18 Javascript
BootstrapValidator不触发校验的实现代码
2016/09/28 Javascript
Form表单按回车自动提交表单的实现方法
2016/11/18 Javascript
bootstrap模态框垂直居中效果
2016/12/03 Javascript
快速实现jQuery多级菜单效果
2017/02/01 Javascript
浅谈React Native 中组件的生命周期
2017/09/08 Javascript
Vue.js实现可配置的登录表单代码详解
2018/03/29 Javascript
解决vue 中 echart 在子组件中只显示一次的问题
2018/08/07 Javascript
JS加密插件CryptoJS实现的DES加密示例
2018/08/16 Javascript
Bootstrap 实现表格样式、表单布局的实例代码
2018/12/09 Javascript
彻底揭秘keep-alive原理(小结)
2019/05/05 Javascript
解决layui 表单元素radio不显示渲染的问题
2019/09/04 Javascript
微信小程序wx.navigateTo方法里的events参数使用详情及场景
2020/01/07 Javascript
js实现时钟定时器
2020/03/26 Javascript
js点击事件的执行过程实例分析【冒泡与捕获】
2020/04/11 Javascript
只有 20 行的 JavaScript 模板引擎实例详解
2020/05/11 Javascript
vue-cli4项目开启eslint保存时自动格式问题
2020/07/13 Javascript
打开电脑上的QQ的python代码
2013/02/10 Python
Python 的 Socket 编程
2015/03/24 Python
Python map及filter函数使用方法解析
2020/08/06 Python
Zooplus葡萄牙:欧洲领先的网上宠物商店
2018/07/01 全球购物
Camper鞋西班牙官方网上商店:西班牙马略卡岛的鞋类品牌
2019/03/14 全球购物
师范生自荐信
2013/10/27 职场文书
科研先进个人典型材料
2014/01/31 职场文书
粗加工管理制度
2014/02/04 职场文书
冰淇淋店的创业计划书
2014/02/07 职场文书
小班秋游活动方案
2014/02/22 职场文书
六年级学生评语
2014/04/22 职场文书
pytorch中的numel函数用法说明
2021/05/13 Python
Element-ui Layout布局(Row和Col组件)的实现
2021/12/06 Vue.js
 python中的元类metaclass详情
2022/05/30 Python