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.

以上这篇Python 实现日志同时输出到屏幕和文件就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 记录Python脚本的运行日志的方法

    一.logging模块 Python中有一个模块logging,可以直接记录日志 # 日志级别 # CRITICAL 50 # ERROR 40 # WARNING 30 # INFO 20 # DEBUG 10 logging.basicConfig()函数中的具体参数: filename:   指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中: filemode:   文件打开方式,在指定了filename时使用这个参数,默认值为"w"还可指定为"

  • 详解python读取和输出到txt

    读取txt的数据和把数据保存到txt中是经常要用到的,下面我就总结一下. 读txt文件 python常用的读取文件函数有三种read().readline().readlines() 以读取上述txt为例,我们一起来看一下三者的区别 read() 一次性读全部内容 read() #一次性读取文本中全部的内容,以字符串的形式返回结果 with open("test.txt", "r") as f: #打开文件 data = f.read() #读取文件 print(d

  • python 实现在shell窗口中编写print不向屏幕输出

    前言 由于需要在python的shell窗口中直接写函数,而函数代码中需要有print,而通常写入print换行后都会向屏幕输出, 所以有了以下解决方案: 例子 其实也什么特别,就是在编写函数时,函数里面的每句代码前面都加上tab进行缩进. 以上这篇python 实现在shell窗口中编写print不向屏幕输出就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们.

  • 对Tensorflow中tensorboard日志的生成与显示详解

    TensorBoard是TensorFlow下的一个可视化的工具,能够帮助我们在训练大规模神经网络过程中出现的复杂且不好理解的运算.TensorBoard能展示你训练过程中绘制的图像.网络结构等. 1. 构建简单的TensorBoard日志输出 import tensorflow as tf input1 = tf.constant([1.0, 2.0, 3.0], name="input1") input2 = tf.Variable(tf.random_uniform([3], n

  • Python的log日志功能及设置方法

    引入:Python中有个logging模块可以完成相关信息的记录,在debug时用它往往事半功倍 一.日志级别(从低到高): DEBUG :详细的信息,通常只出现在诊断问题上 INFO:确认一切按预期运行 WARNING:一个迹象表明,一些意想不到的事情发生了,或表明一些问题在不久的将来(例如.磁盘空间低").这个软件还能按预期工作. ERROR:更严重的问题,软件没能执行一些功能 CRITICAL :一个严重的错误,这表明程序本身可能无法继续运行 注:这5个等级,也分别对应5种打日志的方法:

  • 详解python的几种标准输出重定向方式

    一. 背景 在Python中,文件对象sys.stdin.sys.stdout和sys.stderr分别对应解释器的标准输入.标准输出和标准出错流.在程序启动时,这些对象的初值由sys.__stdin__.sys.__stdout__和sys.__stderr__保存,以便用于收尾(finalization)时恢复标准流对象. Windows系统中IDLE(Python GUI)由pythonw.exe,该GUI没有控制台.因此,IDLE将标准输出句柄替换为特殊的PseudoOutputFile

  • 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 - %(nam

  • Python+logging输出到屏幕将log日志写入文件

    日志 日志是跟踪软件运行时所发生的事件的一种方法.软件开发者在代码中调用日志函数,表明发生了特定的事件.事件由描述性消息描述,该描述性消息可以可选地包含可变数据(即,对于事件的每次出现都潜在地不同的数据).事件还具有开发者归因于事件的重要性:重要性也可以称为级别或严重性. logging提供了一组便利的函数,用来做简单的日志.它们是 debug(). info(). warning(). error() 和 critical(). logging函数根据它们用来跟踪的事件的级别或严重程度来命名.

  • Python向日志输出中添加上下文信息

    除了传递给日志记录函数的参数(如msg)外,有时候我们还想在日志输出中包含一些额外的上下文信息.比如,在一个网络应用中,可能希望在日志中记录客户端的特定信息,如:远程客户端的IP地址和用户名.这里我们来介绍以下几种实现方式: 通过向日志记录函数传递一个extra参数引入上下文信息 使用LoggerAdapters引入上下文信息 使用Filters引入上下文信息 一.通过向日志记录函数传递一个extra参数引入上下文信息 前面我们提到过,可以通过向日志记录函数传递一个extra参数来实现向日志输出

  • Python loguru日志库之高效输出控制台日志和日志记录

    1安装loguru loguru的PyPI地址为:https://pypi.org/project/loguru/ GitHub仓库地址为:https://github.com/Delgan/loguru 我们可以直接使用pip命令对其进行安装 pip install loguru 或者下载其源码,使用Python命令进行安装. |2loguru简单使用 from loguru import logger logger.info("中文loguru") logger.debug(&qu

  • Python日志:自定义输出字段 json格式输出方式

    最近有一个需求:将日志以json格式输出, 并且有些字段是logging模块没有的.看了很多源码和资料, 终于搞定, 抽取精华分享出来, 一起成长. import json import logging class JsonFilter(logging.Filter): ip = 'IP' source = 'APP' def filter(self, record): record.ip = self.ip record.username = self.source return True i

  • python logging多进程多线程输出到同一个日志文件的实战案例

    参考官方案例:https://docs.python.org/zh-cn/3.8/howto/logging-cookbook.html import logging import logging.config import logging.handlers from multiprocessing import Process, Queue import random import threading import time def logger_thread(q): while True:

  • 怎样使用Python脚本日志功能

    假设要开发一个自动化脚本工具,工程结构如下,Common这个package是框架功能的实现,Scripts目录是我们编写的测试用例脚本(请忽略其他不相关的目录). 我们对日志功能的需求如下:      1 为了便于日志的查看,每个脚本对应一个日志文件,日志文件以脚本的名字命名      2 日志路径以及每个脚本保存的日志容量可以设置,比如设置为5MB,则超过后最老日志被自动覆盖      3 日志功能要使用方便,减少与框架业务功能的耦合 现在来逐一分析上述需求. 1 要实现每个脚本一个日志文件,

  • python 信息同时输出到控制台与文件的实例讲解

    python编程中,往往需要将结果用print等输出,如果希望输出既可以显示到IDE的屏幕上,也能存到文件中(如txt)中,该怎么办呢? 方法1 可通过日志logging模块输出信息到文件或屏幕.但可能要设置log的level或输出端,对于同时需要记录debug error等信息的较为合适,官方教程推荐学习用更规范的logger来操作. 例如,可参考来自官网的这段代码. import logging logging.basicConfig(filename='log_examp.log',lev

  • Python Logging 日志记录入门学习

    Python Logging原来真的远比我想象的要复杂很多很多,学习路线堪比git.但是又绕不过去,alternatives又少,所以必须要予以重视,踏踏实实认认真真的来好好学学才行. 学习Logging的目的: 简单脚本还好,print足够. 但是稍微复杂点,哪怕是三四个文件加起来两三百行代码,调试也开始变复杂起来了. 再加上如果是后台长期运行的那种脚本,运行信息的调查更是复杂起来. 一开始我还在各种查crontab的日志查看,或者是python后台运行查看,或者是python stdout的

  • 详解python logging日志传输

    1.生成日志并通过http传输出去(通过HTTPHandler方式): #生成并发送日志 import logging from logging.handlers import HTTPHandler import logging.config def save(): logger = logging.getLogger(__name__) # 生成一个log实例,如果括号为空则返回root logger hh = HTTPHandler(host='127.0.0.1:5000', url='

随机推荐