广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python之强大的日志模块
  • 825
分享到

python之强大的日志模块

模块强大日志 2023-01-31 01:01:13 825人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

作者:txw1958 | 出处:博客园 | 2011/10/21 19:41:55 | 阅读43次 1.简单的将日志打印到屏幕   import logging logging.debug('This is debug message

作者:txw1958 | 出处:博客园 | 2011/10/21 19:41:55 | 阅读43次

1.简单的将日志打印到屏幕

 

import logging

logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')

 

屏幕上打印:
WARNING:root:This is warning message

默认情况下,logging将日志打印到屏幕,日志级别为WARNING;
日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,当然也可以自己定义日志级别。

2.通过logging.basicConfig函数对日志的输出格式及方式做相关配置

import logging

logging.basicConfig(level=logging.DEBUG,
                fORMat='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename='myapp.log',
                filemode='w')
    
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')

 

./myapp.log文件中内容为:
Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug message
Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message
Sun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message

logging.basicConfig函数各参数:
filename: 指定日志文件名
filemode: 和file函数意义相同,指定日志文件的打开模式,'w'或'a'
format: 指定输出的格式和内容,format可以输出很多有用信息,如上例所示:
 %(levelno)s: 打印日志级别的数值
 %(levelname)s: 打印日志级别名称
 %(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
 %(filename)s: 打印当前执行程序名
 %(funcName)s: 打印日志的当前函数
 %(lineno)d: 打印日志的当前行号
 %(asctime)s: 打印日志的时间
 %(thread)d: 打印线程ID
 %(threadName)s: 打印线程名称
 %(process)d: 打印进程ID
 %(message)s: 打印日志信息
datefmt: 指定时间格式,同time.strftime()
level: 设置日志级别,默认为logging.WARNING
stream: 指定将日志的输出流,可以指定输出到sys.stderr,sys.stdout或者文件,默认输出到sys.stderr,当stream和filename同时指定时,stream被忽略

3.将日志同时输出到文件和屏幕

import logging

logging.basicConfig(level=logging.DEBUG,
                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename='myapp.log',
                filemode='w')

#################################################################################################
#定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象#
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
#################################################################################################

logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')

 

屏幕上打印:
root        : INFO     This is info message
root        : WARNING  This is warning message

./myapp.log文件中内容为:
Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug message
Sun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info message
Sun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message

4.logging之日志回滚

import logging
from logging.handlers import RotatingFileHandler

#################################################################################################
#定义一个RotatingFileHandler,最多备份5个日志文件,每个日志文件最大10M
Rthandler = RotatingFileHandler('myapp.log', maxBytes=10*1024*1024,backupCount=5)
Rthandler.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
Rthandler.setFormatter(formatter)
logging.getLogger('').addHandler(Rthandler)
################################################################################################

从上例和本例可以看出,logging有一个日志处理的主对象,其它处理方式都是通过addHandler添加进去的。
logging的几种handle方式如下:

 

logging.StreamHandler: 日志输出到流,可以是sys.stderr、sys.stdout或者文件
logging.FileHandler: 日志输出到文件

日志回滚方式,实际使用时用RotatingFileHandler和TimedRotatingFileHandler
logging.handlers.BaseRotatingHandler
logging.handlers.RotatingFileHandler
logging.handlers.TimedRotatingFileHandler

logging.handlers.SocketHandler: 远程输出日志到tcp/IP sockets
logging.handlers.DatagramHandler:  远程输出日志到UDP sockets
logging.handlers.SMTPHandler:  远程输出日志到邮件地址
logging.handlers.SysLogHandler: 日志输出到syslog
logging.handlers.NTEventLogHandler: 远程输出日志到windows NT/2000/XP的事件日志
logging.handlers.MemoryHandler: 日志输出到内存中的制定buffer
logging.handlers.HttpHandler: 通过"GET"或"POST"远程输出到HTTP服务器

 

由于StreamHandler和FileHandler是常用的日志处理方式,所以直接包含在logging模块中,而其他方式则包含在logging.handlers模块中,
上述其它处理方式的使用请参见python2.5手册!

5.通过logging.config模块配置日志

#logger.conf

###############################################

[loggers]
keys=root,example01,example02

[logger_root]
level=DEBUG
handlers=hand01,hand02

[logger_example01]
handlers=hand01,hand02
qualname=example01
propagate=0

[logger_example02]
handlers=hand01,hand03
qualname=example02
propagate=0

###############################################

[handlers]
keys=hand01,hand02,hand03

[handler_hand01]
class=StreamHandler
level=INFO
formatter=form02
args=(sys.stderr,)

[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form01
args=('myapp.log', 'a')

[handler_hand03]
class=handlers.RotatingFileHandler
level=INFO
formatter=form02
args=('myapp.log', 'a', 10*1024*1024, 5)

###############################################

[formatters]
keys=form01,form02

[formatter_form01]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt=%a, %d %b %Y %H:%M:%S

[formatter_form02]
format=%(name)-12s: %(levelname)-8s %(message)s
datefmt=

上例3:

import logging
import logging.config

logging.config.fileConfig("logger.conf")
logger = logging.getLogger("example01")

logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')

上例4:

import logging
import logging.config

logging.config.fileConfig("logger.conf")
logger = logging.getLogger("example02")

logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')

6.logging是线程安全

7.logging重定向strerr,strout

import logging
import sys
 
class StreamToLogger(object):
   """
   Fake file-like stream object that redirects writes to a logger instance.
   """
   def __init__(self, logger, log_level=logging.INFO):
      self.logger = logger
      self.log_level = log_level
      self.linebuf = ''
 
   def write(self, buf):
      for line in buf.rstrip().splitlines():
         self.logger.log(self.log_level, line.rstrip())
 
logging.basicConfig(
   level=logging.DEBUG,
   format='%(asctime)s:%(levelname)s:%(name)s:%(message)s',
   filename="out.log",
   filemode='a'
)
 
stdout_logger = logging.getLogger('STDOUT')
sl = StreamToLogger(stdout_logger, logging.INFO)
sys.stdout = sl
 
stderr_logger = logging.getLogger('STDERR')
sl = StreamToLogger(stderr_logger, logging.ERROR)
sys.stderr = sl
 
print "Test to standard out"
raise Exception('Test to standard error')



We define a custom file-like object called StreamToLogger object which sends anything written to it to a logger instead. We then create two instances of that object and replace sys.stdout and sys.stderr with our fake file-like instances.

The output logfile looks like this:

2011-08-14 14:46:20,573:INFO:STDOUT:Test to standard out  
2011-08-14 14:46:20,573:ERROR:STDERR:Traceback (most recent call last):  
2011-08-14 14:46:20,574:ERROR:STDERR:  File "redirect.py", line 33, in   
2011-08-14 14:46:20,574:ERROR:STDERR:raise Exception('Test to standard error')  
2011-08-14 14:46:20,574:ERROR:STDERR:Exception  
2011-08-14 14:46:20,574:ERROR:STDERR::  
2011-08-14 14:46:20,574:ERROR:STDERR:Test to standard error  
2011-08-14 14:46:20,573:INFO:STDOUT:Test to standard out
2011-08-14 14:46:20,573:ERROR:STDERR:Traceback (most recent call last):
2011-08-14 14:46:20,574:ERROR:STDERR:  File "redirect.py", line 33, in 
2011-08-14 14:46:20,574:ERROR:STDERR:raise Exception('Test to standard error')
2011-08-14 14:46:20,574:ERROR:STDERR:Exception
2011-08-14 14:46:20,574:ERROR:STDERR::
2011-08-14 14:46:20,574:ERROR:STDERR:Test to standard error

--结束END--

本文标题: python之强大的日志模块

本文链接: https://www.lsjlt.com/news/184379.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python之强大的日志模块
    作者:txw1958 | 出处:博客园 | 2011/10/21 19:41:55 | 阅读43次 1.简单的将日志打印到屏幕   import logging logging.debug('This is debug message...
    99+
    2023-01-31
    模块 强大 日志
  • Python学习之日志模块详解
    目录日志的作用日志的等级logging 模块的使用logging 模块演示小案例OK,今天我们来学习一下 python 中的日志模块,日志模块也是我们日后的开发工作中使用率很高的模块...
    99+
    2022-11-13
  • Python 日志模块logging
    logging模块: logging是一个日志记录模块,可以记录我们日常的操作。 logging日志文件写入默认是gbk编码格式的,所以在查看时需要使用gbk的解码方式打开。 logging日志等级:CRITICAL(50) > E...
    99+
    2023-01-30
    模块 日志 Python
  • Python开发之日志记录模块:logg
    最近在开发一个应用软件,为方便调试和后期维护,在代码中添加了日志,用的是Python内置的logging模块,看了许多博主的博文,颇有所得。不得不说,有许多博主大牛总结得确实很好。似乎我再写关于logging的博文有些多余,但不写总结又...
    99+
    2023-01-31
    模块 日志 Python
  • python日志处理模块
    1 日志级别 日志级别level 数值 CRITICAL 50 ERROR 40 WARNING 30 ,默认日志级别 INFO 20 DEBUG 10 NOTSET 0,表示不设置 日志级别是指...
    99+
    2023-01-31
    模块 日志 python
  • python logging日志模块的详解
    python logging日志模块的详解 日志级别 日志一共分成5个等级,从低到高分别是:DEBUG INFO WARNING ERROR CRITICAL。 DEBUG:详细的信息,通常只出现在诊断...
    99+
    2022-06-04
    详解 模块 日志
  • Python日志模块logging用法
    一、概述 步骤 创建logger对象创建handler对象创建formatter对象把formatter绑定到handler对象上把handler对象绑定到logger对象上设置级别...
    99+
    2022-11-11
  • python日志模块loguru详解
    目录前言使用步骤安装库简单使用方法配置异常追溯总结前言 在部署一些定时运行或者长期运行的任务时,为了留存一些导致程序出现异常或错误的信息,通常会才用日志的方式来进行记录这些信息。py...
    99+
    2022-11-13
  • 详解 python logging日志模块
    目录1.日志简介2.日志级别3.修改日志级别4.日志记录到文件5.指定日志格式6.记录器(logger)7.处理器(Handler)8.处理器操作9.格式器(formatter)10...
    99+
    2022-11-12
  • python 日志模块工具类
    #!/usr/bin/env python # -*- coding: utf-8 -*- import logging # logName 日志中的某个格式化的字段名,logFile生成的日志文件名 def getlogger(...
    99+
    2023-01-30
    模块 工具 日志
  • python 日志模块logging学习
           在日常项目中,总是需要记录下一些细小信息或者错误码、错误信息的,这个时候就需要进行日志的操作。 python中用于日志创建、设置和记录等功能的模块,就是logging了,下面是对其基本使用方法的介绍: 一、最最...
    99+
    2023-01-31
    模块 日志 python
  • python的logging日志模块是什么
    这篇文章给大家介绍python的logging日志模块是什么,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。1.简单的将日志打印到屏幕import logginglogging.debug('This ...
    99+
    2023-06-04
  • python logging日志模块怎么用
    这篇文章主要讲解了“python logging日志模块怎么用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“python logging日志模块怎么用”吧!1.日志简介说...
    99+
    2023-06-29
  • Python中日志模块是什么
    这篇文章主要介绍了Python中日志模块是什么,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。日志的作用说到日志,我们完全可以想象为现实生活中的日记。日记是我们平时记录我们生活...
    99+
    2023-06-29
  • Python强大的自有模块——标准库
    引言:Python的强大体现在“模块自信”上,因为Python不仅有很强大的自有模块(标准库),还有海量的第三方模块(或者包、库),并且很多开发者还在不断贡献在自己开发的新模块(或者包、库)。本文将向大家概述介绍Python的自有模块...
    99+
    2023-01-31
    模块 强大 标准
  • python 3.x 分析日志的模块(正
    #导入正则模块 import re auth="no_shutdown_" ''' 分析日志的模块,查找日志中标志性信息产生的次数 ''' #定义你需要查找的对象的正则表达式wordcheck #需要分析的日志的路径filesource d...
    99+
    2023-01-31
    模块 日志 python
  • Python日志模块logging如何使用
    这篇文章主要讲解了“Python日志模块logging如何使用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Python日志模块logging如何使用”吧!关于开发日志对于开发日志,很多程序...
    99+
    2023-06-30
  • Python日志模块logging怎么使用
    这篇“Python日志模块logging怎么使用”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Python日志模块loggi...
    99+
    2023-06-30
  • 如何理解python接口自动化之logging日志模块
    目录一、logging模块介绍二、日志等级三、日志收集器四、日志处理器五、日志过滤器六、日志格式器七、日志滚动八、模块封装一、logging模块介绍 ​前言:我们之前运行代码时都是将日志直接输出到控制台,...
    99+
    2022-06-02
    python 接口自动化 python logging
  • 怎么用Python实现强大的 logging 模块
    本篇内容介绍了“怎么用Python实现强大的 logging 模块”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有...
    99+
    2022-10-19
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作