日志是非常重要的,最近有接触到这个,所以系统的看一下Python这个模块的用法。本文即为Logging模块的用法简介,主要参考文章为Python官方文档,链接见参考列表。

Logging模块构成

组成

主要分为四个部分:

  • Loggers:提供应用程序直接使用的接口
  • Handlers:将Loggers产生的日志传到指定位置
  • Filters:对输出日志进行过滤
  • Formatters:控制输出格式

日志级别

Level Numeric value When it’s used
DEBUG 10 Detailed information, typically of interest only when diagnosing problems.
INFO 20 Confirmation that things are working as expected.
WARNING 30 An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.
ERROR 40 Due to a more serious problem, the software has not been able to perform some function.
CRITICAL 50 A serious error, indicating that the program itself may be unable to continue running.
NOSET 0 getattr(logging, loglevel.upper())

默认级别是WARNING,可以使用打印到屏幕上的方式记录,也可以记录到文件中。

使用示例

下面的代码展示了logging最基本的用法。

 # import logging
#
# logging.basicConfig(filename="log.txt",
# level=logging.DEBUG,
# format="%(asctime)s %(message)s",
# datefmt="%Y-%m")
# logging.debug("SS") """
%(name)s Logger的名字
%(levelno)s 数字形式的日志级别
%(levename)s 文本形式的日志级别
%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s 调用日志输出函数的模块的文件名
%(module)s 调用日志输出函数的模块名
%(funcName)s 调用日志输出函数的函数名
%(lineno)d 调用日志输出函数的语句所在的代码行
%(created)f 当前时间,用UNIX标准的表示时间的浮点数表示
%(relativeCreated)d 输出日志信息时的,自Logger创建以来的毫秒数
%(asctime)s 字符串形式的当前时间,默认格式是"2003-07-08 16:49:45,896",毫秒
%(thread)d 线程ID,可能没有
%(threadName)s 线程名,可能没有
%(process)d 进程ID,可能没有
%(message)s 用户输出的消息 """ # 同时输出到文件,屏幕
import logging class IgnoreBackupLogFilter(logging.Filter):
"""过滤带db backup 的日志""" def filter(self, record): # 固定写法
# true 不记录
return "db backup" not in record.getMessage() # 1、生成logger对象
logger = logging.getLogger("web")
logger.setLevel(logging.DEBUG) # 默认是warning
# 1、1 把filter对象添加到logger中
logger.addFilter(IgnoreBackupLogFilter()) # 2、生成handler对象
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# fh = logging.FileHandler("web.log") # 写到那个文件下
from logging import handlers
fh = handlers.TimedRotatingFileHandler("web.log",when="S",interval=5,backupCount=3)
fh.setLevel(logging.WARNING)
# 2.1 把handler对象 绑定到logger
logger.addHandler(ch)
logger.addHandler(fh) # 3、生成formatter对象
console_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(filename)s - %(message)s ")
file_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(lineno)d - %(filename)s - %(message)s ")
# 3、1 把formatter对象 绑定到handler对象
ch.setFormatter(console_formatter)
fh.setFormatter(file_formatter) logger.debug("s")
logger.info("d")
logger.warning("g")
logger.error("a324")
logger.info("db backup 2314") # globl debug
# console info
# file warning # 全局设置为DEBUG后,console handler 设置为INFO,如果输出的日志级别是debug,那就不输出 """
日志自动截断
"""
# 按文件大小截断
# from logging import handlers
# fh = handlers.RotatingFileHandler("web.log", maxBytes=100, backupCount=13) # 文件最大100个字节,最多保留3个文件,时间最早的删除
# 按时间长短截断
# from logging import handlers
# fh = handlers.TimedRotatingFileHandler("web.log",when="S",interval=5,backupCount=3)

Python模块之 - logging的更多相关文章

  1. python 模块之-logging

    python  模块logging import logging ###  简单使用格式    日志级别等级CRITICAL > ERROR > WARNING > INFO > ...

  2. python初步学习-python模块之 logging

    logging 许多应用程序中都会有日志模块,用于记录系统在运行过程中的一些关键信息,以便于对系统的运行状况进行跟踪.在python中,我们不需要第三方的日志组件,python为我们提供了简单易用.且 ...

  3. Python模块学习 ---- logging 日志记录

    许多应用程序中都会有日志模块,用于记录系统在运行过程中的一些关键信息,以便于对系统的运行状况进行跟踪.在.NET平台中,有非常著名的第三方开源日志组件log4net,c++中,有人们熟悉的log4cp ...

  4. Python 模块之Logging——常用handlers的使用

    一.StreamHandler 流handler——包含在logging模块中的三个handler之一. 能够将日志信息输出到sys.stdout, sys.stderr 或者类文件对象(更确切点,就 ...

  5. python模块之logging

    在现实生活中,记录日志非常重要.银行转账时会有转账记录:飞机飞行过程中,会有黑盒子(飞行数据记录器)记录飞行过程中的一切.如果有出现什么问题,人们可以通过日志数据来搞清楚到底发生了什么.对于系统开发. ...

  6. 【python模块】——logging

    python学习——logging模块

  7. Python模块:logging、

    logging模块: 很多程序都有记录日志的需求,并且日志中包含的信息既有正常的程序访问日志,还可能有错误.警告等信息输出.Python的logging模块提供了标准的日志接口,你可以通过它存储各种格 ...

  8. python模块学习 logging

    1.简单的将日志打印到屏幕 import logging logging.debug('This is debug message') logging.info('This is info messa ...

  9. python模块:logging

    # Copyright 2001-2016 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and ...

随机推荐

  1. 初始CSS3

    初始CSS31.1.什么是CSSCSS全程为层叠样式表(Cascading Style Sheet),通常又称为风格样式表(Style Sheet)它是用来进行网页风格设计的.1.CSS在网页中的应用 ...

  2. Mysql中一级缓存二级缓存区别

    一级缓存: 也称本地缓存,sqlSession级别的缓存.一级缓存是一直开启的:与数据库同一次会话期间查询到的数据会放在本地缓存中. 如果需要获取相同的数据,直接从缓存中拿,不会再查数据库. 一级缓存 ...

  3. C# MVC NPOI导出

    前台: <form id="fmexp" method="post" target="_blank"> </form> ...

  4. Python中的SQLAlchemy

    在Python中,使用SQLAlchemy可以对数据库进行操作. SQLAlchemy是Python中的一个标准库. 要使用SQLAlchemy,首先要创建连接: url = mysql+pymysq ...

  5. c语言最后一次作业

    1.当初你是如何做出选择计算机专业的决定的? 我再来到大学之前,通过查询和询问,了解到当前计算机行业就业需求量较高,同时我对计算机的几年过去比较高了,在高中时期就有过在大学学习计算机行业的知识与专业的 ...

  6. 福州大学W班-团队作业-随堂小测(同学录)成绩

    作业链接 https://edu.cnblogs.com/campus/fzu/FZUSoftwareEngineering1715W/homework/1246 作业要求 1.题目 即编写一个能够记 ...

  7. Beta No.4

    今天遇到的困难: 百度位置假死的问题研究发现并不是源于代码的问题,而是直接运行在主线程中会出现诸多问题 Fragment碎片刷新时总产生的固定位置的问题未果 今天完成的任务: 陈甘霖:修复了部分Bug ...

  8. 201621123043 《Java程序设计》第8周学习总结

    1. 本周学习总结 2. 书面作业 1. ArrayList代码分析 1.1 解释ArrayList的contains源代码 contains的源代码如下 public boolean contain ...

  9. cpp常用函数总结

    //sprintf sprintf(temp_str_result, "%lf", temp_double); result = temp_str_result; (*begin) ...

  10. linux 50个常用命令

    1.ls命令 ls是list的缩写,常用命令为ls(显示出当前目录列表),ls -l(详细显示当前目录列表),ls -lh(人性化的详细显示当前目录列表),ls -a(显示出当前目录列表,包含隐藏文件 ...