python-- logging 模块

本文涉及的产品
日志服务 SLS,月写入数据量 50GB 1个月
简介: python-- logging 模块

前戏


import logging
logging.debug('debug message')  # 调试模式
logging.info('info message')  # 基础信息
logging.warning('warning message')  # 警告
logging.error('error message')  # 错误
logging.critical('critical message')  # 严重错误

结果:

WARNING:root:warning message
ERROR:root:error message
CRITICAL:root:critical message

打印出了warning及以上的信息,python解释器默认的


设置日志级别


import logging
logging.basicConfig(level=logging.DEBUG)  # 设置输出的日志级别
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')

结果:

DEBUG:root:debug message
INFO:root:info message
WARNING:root:warning message
ERROR:root:error message
CRITICAL:root:critical message


将日志写到文件


import logging
logging.basicConfig(filename='exa.log', level=logging.INFO)
logging.debug('this message should go to the log file')
logging.info('so should this')
logging.warning('And this,too')

这句中的level=loggin.INFO意思是,把日志纪录级别设置为INFO,也就是说,只有比日志是INFO或比INFO级别更高的日志才会被纪录到文件里,在这个例子, 第一条日志是不会被纪录的,如果希望纪录debug的日志,那把日志级别改成DEBUG就行了。


给日志加上时间


import logging
logging.basicConfig(filename='exa.log', level=logging.INFO, format='%(asctime)s %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p')
logging.debug('this message should go to the log file')
logging.info('so should this')
logging.warning('And this,too')

结果

2020-09-20 22:08:26 PM so should this
2020-09-20 22:08:26 PM And this,too


把日志同时打印在屏幕上和写在日志里


import logging
logger = logging.getLogger('TEST-LOG')
logger.setLevel(logging.INFO)  # 设置一个全局的日志级别,局部的比全局的级别低时,以全局的为准
ch = logging.StreamHandler()  # 往屏幕上输出日志
ch.setLevel(logging.DEBUG)  # 屏幕上的日志级别设置为debug
fh = logging.FileHandler("access.log")
# 往文件里输出日志
fh.setLevel(logging.WARNING)  # 文件里的日志级别     为warning
# 定义日志格式,%(name)s是上面定义的这个值
# %(lineno)d 哪一行打印的日志
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_formatter = logging.Formatter('%(asctime)s  -%(lineno)d- %(levelname)s - %(message)s')
# 添加formatter到屏幕和文件里
ch.setFormatter(formatter)
fh.setFormatter(file_formatter)
# 添加屏幕和文件日志到logger里
logger.addHandler(ch)
logger.addHandler(fh)
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')

结果:

屏幕上
2018-05-19 13:57:22,611 - TEST-LOG - INFO - info message
2018-05-19 13:57:22,611 - TEST-LOG - WARNING - warn message
2018-05-19 13:57:22,611 - TEST-LOG - ERROR - error message
2018-05-19 13:57:22,612 - TEST-LOG - CRITICAL - critical message
文件access.log里
2018-05-19 14:03:54,785  -29- WARNING - warn message
2018-05-19 14:03:54,785  -30- ERROR - error message
2018-05-19 14:03:54,785  -31- CRITICAL - critical message

import logging
# create logger
logger = logging.getLogger('TEST-LOG')
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create file handler and set level to warning
fh = logging.FileHandler("access.log")
fh.setLevel(logging.WARNING)
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# add formatter to ch and fh
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add ch and fh to logger
logger.addHandler(ch)
logger.addHandler(fh)
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')

结果:

2020-09-20 22:10:41,825 - TEST-LOG - DEBUG - debug message
2020-09-20 22:10:41,825 - TEST-LOG - INFO - info message
2020-09-20 22:10:41,825 - TEST-LOG - WARNING - warn message
2020-09-20 22:10:41,825 - TEST-LOG - ERROR - error message
2020-09-20 22:10:41,825 - TEST-LOG - CRITICAL - critical message

创建一个logger对象

创建一个文件管理操作符

创建一个屏幕管理操作符

创建一个日志输出的格式

文件管理操作符 绑定一个 格式

屏幕管理操作符 绑定一个 格式

logger对象 绑定 文件管理操作符

logger对象 绑定 屏幕管理操作符

import logging
# 创建一个logger对象
logger = logging.getLogger()
# 创建一个文件管理操作符
fh = logging.FileHandler('logger.log', encoding='utf-8')
# 创建一个屏幕管理操作符
sh = logging.StreamHandler()
# 创建一个日志输出的格式
format1 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# 文件管理操作符 绑定一个 格式
fh.setFormatter(format1)
# 屏幕管理操作符 绑定一个 格式
sh.setFormatter(format1)
logger.setLevel(logging.DEBUG)
# logger对象 绑定 文件管理操作符
# logger.addHandler(fh)
# logger对象 绑定 屏幕管理操作符
logger.addHandler(sh)
logger.debug('debug message')  # 调试模式
logger.info('我的信息')  # 基础信息
logger.warning('warning message')  # 警告
logger.error('error message')  # 错误
logger.critical('critical message')  # 严重错误

结果:

2020-09-20 22:11:36,115 - root - DEBUG - debug message
2020-09-20 22:11:36,115 - root - INFO - 我的信息
2020-09-20 22:11:36,115 - root - WARNING - warning message
2020-09-20 22:11:36,115 - root - ERROR - error message
2020-09-20 22:11:36,115 - root - CRITICAL - critical message

import logging
from logging import handlers
logger = logging.getLogger(__name__)
log_file = "timelog.log"
fh = handlers.TimedRotatingFileHandler(filename=log_file, when="S", interval=5, backupCount=3)
formatter = logging.Formatter('%(asctime)s %(module)s:%(lineno)d %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
logger.warning("test1")
logger.warning("test12")
logger.warning("test13")
logger.warning("test14")

结果:

2020-09-20 22:13:10,481 tests:17 test1
2020-09-20 22:13:10,483 tests:18 test12
2020-09-20 22:13:10,483 tests:19 test13
2020-09-20 22:13:10,483 tests:20 test14

相关文章
|
1月前
|
SQL 关系型数据库 数据库
Python SQLAlchemy模块:从入门到实战的数据库操作指南
免费提供Python+PyCharm编程环境,结合SQLAlchemy ORM框架详解数据库开发。涵盖连接配置、模型定义、CRUD操作、事务控制及Alembic迁移工具,以电商订单系统为例,深入讲解高并发场景下的性能优化与最佳实践,助你高效构建数据驱动应用。
270 7
|
1月前
|
监控 安全 程序员
Python日志模块配置:从print到logging的优雅升级指南
从 `print` 到 `logging` 是 Python 开发的必经之路。`print` 调试简单却难维护,日志混乱、无法分级、缺乏上下文;而 `logging` 支持级别控制、多输出、结构化记录,助力项目可维护性升级。本文详解痛点、优势、迁移方案与最佳实践,助你构建专业日志系统,让程序“有记忆”。
215 0
|
1月前
|
JSON 算法 API
Python中的json模块:从基础到进阶的实用指南
本文深入解析Python内置json模块的使用,涵盖序列化与反序列化核心函数、参数配置、中文处理、自定义对象转换及异常处理,并介绍性能优化与第三方库扩展,助你高效实现JSON数据交互。(238字)
294 4
|
1月前
|
Java 调度 数据库
Python threading模块:多线程编程的实战指南
本文深入讲解Python多线程编程,涵盖threading模块的核心用法:线程创建、生命周期、同步机制(锁、信号量、条件变量)、线程通信(队列)、守护线程与线程池应用。结合实战案例,如多线程下载器,帮助开发者提升程序并发性能,适用于I/O密集型任务处理。
226 0
|
1月前
|
XML JSON 数据处理
超越JSON:Python结构化数据处理模块全解析
本文深入解析Python中12个核心数据处理模块,涵盖csv、pandas、pickle、shelve、struct、configparser、xml、numpy、array、sqlite3和msgpack,覆盖表格处理、序列化、配置管理、科学计算等六大场景,结合真实案例与决策树,助你高效应对各类数据挑战。(238字)
163 0
|
2月前
|
安全 大数据 程序员
Python operator模块的methodcaller:一行代码搞定对象方法调用的黑科技
`operator.methodcaller`是Python中处理对象方法调用的高效工具,替代冗长Lambda,提升代码可读性与性能。适用于数据过滤、排序、转换等场景,支持参数传递与链式调用,是函数式编程的隐藏利器。
116 4
|
2月前
|
存储 数据库 开发者
Python SQLite模块:轻量级数据库的实战指南
本文深入讲解Python内置sqlite3模块的实战应用,涵盖数据库连接、CRUD操作、事务管理、性能优化及高级特性,结合完整案例,助你快速掌握SQLite在小型项目中的高效使用,是Python开发者必备的轻量级数据库指南。
276 0
|
3月前
|
存储 安全 数据处理
Python 内置模块 collections 详解
`collections` 是 Python 内置模块,提供多种高效数据类型,如 `namedtuple`、`deque`、`Counter` 等,帮助开发者优化数据处理流程,提升代码可读性与性能,适用于复杂数据结构管理与高效操作场景。
316 0
|
4月前
|
数据安全/隐私保护 Python
抖音私信脚本app,协议私信群发工具,抖音python私信模块
这个实现包含三个主要模块:抖音私信核心功能类、辅助工具类和主程序入口。核心功能包括登录
|
7月前
|
Python
Python教程:os 与 sys 模块详细用法
os 模块用于与操作系统交互,主要涉及夹操作、路径操作和其他操作。例如,`os.rename()` 重命名文件,`os.mkdir()` 创建文件夹,`os.path.abspath()` 获取文件绝对路径等。sys 模块则用于与 Python 解释器交互,常用功能如 `sys.path` 查看模块搜索路径,`sys.platform` 检测操作系统等。这些模块提供了丰富的工具,便于开发中处理系统和文件相关任务。
332 14

推荐镜像

更多
下一篇
oss云网关配置