Python 中 logging 日志模块在多进程环境下的使用
因为我的个人网站 restran.net 已经启用,博客园的内容已经不再更新。请访问我的个人网站获取这篇文章的最新内容,Python 中 logging 日志模块在多进程环境下的使用
使用 Python 来写后台任务时,时常需要使用输出日志来记录程序运行的状态,并在发生错误时将错误的详细信息保存下来,以别调试和分析。Python 的 logging 模块就是这种情况下的好帮手。
logging 模块可以指定日志的级别,DEBUG、INFO、WARNING、ERROR、CRITICAL,例如可以在开发和调试时,把 DEBUG 以上级别的日志都输出,而在生产环境下,只输出 INFO 级别。(如果不特别指定,默认级别是 warning)
logging 还可以指定输出到命令行或者文件,还可以按时间或大小分割日志文件。
关于 logging 的详细使用,这里就不再细说,可以参考官方文档,或者这里的介绍。
logging 的配置
通常情况下,我们需要将日志保存到文件中,并期望能自动分割文件,避免日志文件太大。下面给出了一个 logging 的配置例子。
import logging.config
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'verbose': {
'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt': "%Y-%m-%d %H:%M:%S"
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'null': {
'level': 'DEBUG',
'class': 'logging.NullHandler',
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose'
},
'file': {
'level': 'DEBUG',
'class': 'logging.RotatingFileHandler',
# 当达到10MB时分割日志
'maxBytes': 1024 * 1024 * 10,
# 最多保留50份文件
'backupCount': 50,
# If delay is true,
# then file opening is deferred until the first call to emit().
'delay': True,
'filename': 'logs/mysite.log',
'formatter': 'verbose'
}
},
'loggers': {
'': {
'handlers': ['file'],
'level': 'info',
},
}
})
我们在一个模块内,就可以这么使用来记录日志
import logging
logger = logging.getLogger(__name__)
if __name__ == '__main__':
logger.info('log info')
多进程环境下的使用
按照官方文档的介绍,logging 是线程安全的,也就是说,在一个进程内的多个线程同时往同一个文件写日志是安全的。但是(对,这里有个但是)多个进程往同一个文件写日志不是安全的。官方的说法是这样的:
Because there is no standard way to serialize access to a single file across multiple processes in Python. If you need to log to a single file from multiple processes, one way of doing this is to have all the processes log to a SocketHandler, and have a separate process which implements a socket server which reads from the socket and logs to file. (If you prefer, you can dedicate one thread in one of the existing processes to perform this function.)
有的人会说,那我不用多进程不就可以了。但是 Python 有一个 GIL 的大锁(关于 GIL 的纠葛可以看这里),使用多线程是没法利用到多核 CPU 的,大部分情况下会改用多进程来利用多核 CPU,因此我们还是绕不开不开多进程下日志的问题。
为了解决这个问题,可以使用 ConcurrentLogHandler,ConcurrentLogHandler 可以在多进程环境下安全的将日志写入到同一个文件,并且可以在日志文件达到特定大小时,分割日志文件。在默认的 logging 模块中,有个 TimedRotatingFileHandler 类,可以按时间分割日志文件,可惜 ConcurrentLogHandler 不支持这种按时间分割日志文件的方式。
重新修改下 handlers 中的 class。
logging.config.dictConfig({
...
'handlers': {
'file': {
'level': 'DEBUG',
# 如果没有使用并发的日志处理类,在多实例的情况下日志会出现缺失
'class': 'cloghandler.ConcurrentRotatingFileHandler',
# 当达到10MB时分割日志
'maxBytes': 1024 * 1024 * 10,
# 最多保留50份文件
'backupCount': 50,
# If delay is true,
# then file opening is deferred until the first call to emit().
'delay': True,
'filename': 'logs/mysite.log',
'formatter': 'verbose'
}
},
...
})
运行后可以发现,会自动创建一个.lock文件,通过锁的方式来安全的写日志文件。
Python 中 logging 日志模块在多进程环境下的使用的更多相关文章
- Python中logging日志模块的使用
参考https://www.cnblogs.com/CJOKER/p/8295272.html
- python的logging日志模块(一)
最近修改了项目里的logging相关功能,用到了Python标准库里的logging模块,在此做一些记录.主要是从官方文档和stackoverflow上查询到的一些内容. 官方文档 技术博客 基本用法 ...
- Python入门之logging日志模块以及多进程日志
本篇文章主要对 python logging 的介绍加深理解.更主要是 讨论在多进程环境下如何使用logging 来输出日志, 如何安全地切分日志文件. 1. logging日志模块介绍 python ...
- python中的日志模块logging
1.日志级别5个: 警告Warning 一般信息Info 调试 Debug 错误Error 致命Critical 2.禁用日志方法 logging.disable(logging.DEBUG) 3 ...
- 【python】logging日志模块写入中文编码错误解决办法
一.问题: 使用python的logging模块记录日志,有时会遇到中文编码问题错误. 二.解决办法: 在logging.FileHandler(path) 中添加指定编码方式 encoding='u ...
- python的logging日志模块(二)
晚上比较懒,直接搬砖了. 1.简单的将日志打印到屏幕 import logging logging.debug('This is debug message') logging.info('Thi ...
- python中logging日志基本用法,和进程安全问题
低配版 import logging logging.debug('debug message') # 调试模式 logging.info('info message') # 正常运转模式 loggi ...
- python(6)-logging 日志模块
logging的日志分为5个级别分别为debug(), info(), warning(), error(), critical() 先来看一下简单的代码: logging.basicConfig(f ...
- python的logging日志模块
1. 简单的将日志打印到屏幕 import logging logging.debug('This is debug message') logging.info('This is info mess ...
随机推荐
- 对于应用之间的调用,如何选择rpc还是mq?
两个系统之间的调用,是选择rpc呢还是mq,说一下你们系统的选择吧 比如rpc可以是简单的spring httpinvoker,但是前提是都是java应用而且都是用spring framework,可 ...
- 使用Bootstrap插件datapicker获取时间
引入css和js <link rel="stylesheet" href="/${appName}/commons/css/datapicker/datepicke ...
- Andrew and Taxi CodeForces - 1100E (思维,拓扑)
大意: 给定有向图, 每条边有一个权值, 假设你有$x$个控制器, 那么可以将所有权值不超过$x$的边翻转, 求最少的控制器数, 使得翻转后图无环 先二分转为判定问题. 每次check删除能动的边, ...
- Java队列的两种实现方式
1. 基于数组 package Algorithm.learn; import java.util.Arrays; /** * Created by liujinhong on 2017/3/7. * ...
- vue-cli如何添加多种环境变量
vue-cli如何添加多种环境变量 目前webpack(vue-cli) 打包有两种变量,development, productor, 如何添加一个 test的测试环境呢 vue-cli 3.0 v ...
- axios请求requestBody和formData
前言 在vue的后台管理开发中,应需求,需要对信息做一个校验,需要将参数传递两份过去,一份防止在body中,一份防止在formdata中,axios请求会默认将参数放在formdata中进行发送. 对 ...
- 7-19 PAT Judge(25 分)
The ranklist of PAT is generated from the status list, which shows the scores of the submissions. Th ...
- 重新学习之spring第四个程序,整合struts2+hibernate+spring
第一步:导入三大框架的jar包(struts2.3.16.1+hibernate3.2+spring3.2.4) 第二步:编写web.xml 和struts.xml和applicationContex ...
- LG4717 【模板】快速沃尔什变换
题意 题目描述 给定长度为\(2^n\)两个序列\(A,B\),设\(C_i=\sum_{j\oplus k}A_jB_k\)分别当\(\oplus\)是or,and,xor时求出C 输入输出格式 输 ...
- 华硕主板P8H61(P8H61-M_LX3_PLUS_R2.0)成功禁用USB口
公司大批这个型号的主板,在百度上搜索了一下,其中有一篇帖子说华硕客服说这个型号的USB控制XX是集成成南桥上面没法禁止. 经过研究发现官网上的0802版可以支持禁止usb,并且可以根据需要为每一个US ...