Python 实现日志同时输出到屏幕和文件
作者:ForeverStrong 发布时间:2021-06-25 23:04:29
标签:Python,日志输出,屏幕,文件
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.
来源:https://blog.csdn.net/chengyq116/article/details/93765575


猜你喜欢
- 在用Python开发时(Windows环境),会碰到需要安装某个版本的第三方库,为了以后查找、安装方便,总结如下:windows版的各种Py
- 代码如下:CREATE FUNCTION dbo.f_splitstr( @str varchar(8000) )RETURNS
- 本文实例讲述了Python常见数据结构之栈与队列用法。分享给大家供大家参考,具体如下:Python常见数据结构之-栈首先,栈是一种数据结构。
- 一、多层索引1.创建环境:Jupyterimport numpy as npimport pandas as pda=pd.DataFram
- 导言(Introduction)这个提案描述了如何在jQuery的核心库中增加模板支持。更为特别是,这个提案描述了一个新的jQuery方法-
- 1、 数据库闭包表简介像MySQL这样的关系型数据库,比较适合存储一些类似表格的扁平化数据,但是遇到像树形结构这样有深度的数据,就很难驾驭了
- 前言最近几天,研究了一下一直很好奇的爬虫算法。这里写一下最近几天的点点心得。下面进入正文:你可能需要的工作环境:Python 3.6官网下载
- 使用distinct在mysql中查询多条不重复记录值的解决办法如何使用distinct在mysql中查询多条不重复记录值?有时候想用dis
- 之前写了一个matlab的,越用越觉得麻烦,如果不同数据集要改类别数目,而且运行速度慢。所以重新写了一个Python的,直接读取xml文件夹
- 在官方网站中对as_index有以下介绍:as_index : boolean, default TrueFor aggregated ou
- 设置cookie每个cookie都是一个名/值对,可以把下面这样一个字符串赋值给document.cookie:document.cooki
- 1. 介绍 SQLite 是一个开源的嵌入式关系数据库,实现自包容、零配置、支持事务的SQL数据库引擎。 其特点是高度便携、使用方便、结构紧
- 目录1)连接请求的变量1、max_connections2、back_log3、wait_timeout和interative_timeou
- 1. document.form.item 问题 (1)现有问题:现有代码中存在许多 document.formName.item(&quo
- 某天在群内有同学问到,在python下我用input或者raw_input都得输入完后回车才能获取到输入的值,那如何实现任意键退出暂停等功能
- 栅格系统的形成1692年,新登基的法国国王路易十四感到法国的印刷水平强差人意,因此命令成立一个管理印刷的皇家特别委员会。他们的首要任务是设计
- 开门见山自动化测试过程中,一般测试结果都会以邮件的形式发送给相关人员,那么,在Python中,如何编写代码将邮件发送给对应的用户?同时,发送
- urllib 是 python 的内置模块, 主要用于处理url相关的一些操作,例如访问url、解析url等操作。urllib 包下面的 r
- 前言Python经常被称作“胶水语言”,因为它能够轻易地操作其他程序,轻易地包装使用其他语言编写的库。在Python/wxPython环境下
- 本文实例讲述了PHP global全局变量的使用与注意事项。分享给大家供大家参考,具体如下:使用global在方法里面声明外部变量为全局变量