python中日志logging模块的性能及多进程详解

yipeiwu_com7年前Python基础

前言

Java 中最通用的日志模块莫过于 Log4j 了,在 python 中,也自带了 logging 模块,该模块的用法其实和 Log4j 类似。日志是记录操作的一种好方式。但是日志,基本都是基于文件的,也就是要写到磁盘上的。这时候,磁盘将会成为一个性能瓶颈。对于普通的服务器硬盘(机械磁盘,非固态硬盘),Python日志的性能瓶颈是多少呢?今天我们就来测一下。下面话不多说,来一起看看详细的介绍:

测试代码如下:

#! /usr/bin/env python 
#coding=utf-8 
 
# ============================ 
# Describe : 给平台提供的日志 
# D&P Author By:  常成功 
# Create Date:  2016/08/01 
# Modify Date:  2016/08/01 
# ============================ 
 
import time 
import os 
import logging 
 
 
print "Start test ...." 
s_tm = time.time() 
test_time = 10.0 # 测试时间10秒 
e_tm = s_tm + 10 
j = 0 
 
pid = str(os.getpid()) 
while 1: 
 now_time = time.time() 
 j += 1 
 if now_time > e_tm: 
  break 
 # 生成文件夹 
 lujing = "d:\\test_log" 
 if not os.path.exists(lujing): 
  os.mkdir(lujing) 
 
 fm2 = '%Y%m%d' 
 YMD = time.strftime(fm2, time.localtime(now_time)) 
 
 filename = 'recharge_' + YMD + '.log' 
 log_file = os.path.join(lujing, filename) 
 t = "\t" 
 log_msg = str(j) +t+ str(now_time) +t+ pid 
 
 the_logger = logging.getLogger('recharge_log') 
 f_handler = logging.FileHandler(log_file) 
 the_logger.addHandler(f_handler) 
 the_logger.setLevel(logging.INFO) 
 # To pass exception information, use the keyword argument exc_info with a true value 
 the_logger.info(log_msg, exc_info=False) 
 the_logger.removeHandler(f_handler) 
 
rps = j/test_time 
print rps, "rows per second" 

结果为:

Start test ....

2973.0 rows per second


Python的logging性能:

7200转的机械磁盘,测了几次,每秒的能写入日志的行数(每行就是一条日志),数量基本在 2800-3000 之间。此时,磁盘IO基本已经跑满。(在3.3Ghz的CPU上,CPU占用大约40%)。

Python的logging多进程:

python 的 logging模块,是线程安全的。但对于多进程的程序来说,怎么去写日志文件呢?我的解决办法是,每个进程的PID,写一个单独的日志文件。再用算法把所有进程的日志合并起来,生成新的日志。

提示:由于磁盘IO已经到达瓶颈,所以多进程并不能提高日志性能。高性能日志,需要用缓存,或者分布式日志。

总结

以上就是这篇文章的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对【听图阁-专注于Python设计】的支持。

相关文章

Python3简单实现串口通信的方法

如下所示: import serial import sys import os import time import re def wait_for_cmd_OK(): &nb...

python数组过滤实现方法

本文实例讲述了python数组过滤实现方法。分享给大家供大家参考。具体如下: 这段代码可以按照指定的条件过滤数组内的元素,返回过滤后的数组 li = ["a", "mpilgrim"...

Python判断直线和矩形是否相交的方法

本文实例讲述了Python判断直线和矩形是否相交的方法。分享给大家供大家参考。具体实现方法如下: """ A(ax,ay),B(px,py)为两个点 (x1,y1),(x2,y2)为...

使用Python的OpenCV模块识别滑动验证码的缺口(推荐)

使用Python的OpenCV模块识别滑动验证码的缺口(推荐)

最近终于找到一个好的方法,使用Python的OpenCV模块识别滑动验证码的缺口,可以将滑动验证码中的缺口识别出来了。   测试使用如下两张图片:   target....

使用python编写脚本获取手机当前应用apk的信息

前提是已设置ANDROID_HOME环境变量,使用aapt工具获取apk的信息,保存至脚本所在目录下的PackageInfo.txt文件中: import os import te...