python 异步写日志_Python如何异步发送日志到远程服务器?

本文探讨了在Python中遇到的问题,即日志发送到远程服务器时导致的延迟。提出了使用多线程、线程池和异步aiohttp库来解决这个问题。详细介绍了如何使用线程池和aiohttp实现异步发送日志,以避免阻塞主程序,并确保日志顺序。最后,给出了使用aiohttp封装发送数据的函数,并将其注册到事件循环中,实现异步执行并避免脚本卡顿。
摘要由CSDN通过智能技术生成

现在我们考虑一个问题,当日志发送到远程服务器过程中,如果远程服务器处理的很慢,会耗费一定的时间, 那么这时记录日志就会都变慢修改服务器日志处理类,让其停顿5秒钟,模拟长时间的处理流程

async def post(self):

print(self.getParam('log'))

await asyncio.sleep(5)

self.write({"msg": 'ok'})

此时我们再打印上面的日志

logger.debug("今天天气不错")

logger.debug("是风和日丽的")

得到的输出为

[2020-09-23 11:47:33] [DEBUG] 今天天气不错

[2020-09-23 11:47:38] [DEBUG] 是风和日丽的

我们注意到,它们的时间间隔也是5秒。

那么现在问题来了,原本只是一个记录日志,现在却成了拖累整个脚本的累赘,所以我们需要异步的来 处理远程写日志。

1

使用多线程处理

首先想的是应该是用多线程来执行发送日志方法

def emit(self, record):

msg = self.format(record)

if self.method == "GET":

if (self.url.find("?") >= 0):

sep = '&'

else:

sep = '?'

url = self.url + "%c%s" % (sep, urllib.parse.urlencode({"log": msg}))

t = threading.Thread(target=requests.get, args=(url,))

t.start()

else:

headers = {

"Content-type": "application/x-www-form-urlencoded",

"Content-length": str(len(msg))

}

t = threading.Thread(target=requests.post, args=(self.url,), kwargs=

{"data":{'log': msg},

这种方法是可以达到不阻塞主目的,但是每打印一条日志就需要开启一个线程,也是挺浪费资源的。

我们也 可以使用线程池来处理

2

使用线程池处理

python 的 concurrent.futures 中有ThreadPoolExecutor, ProcessPoolExecutor类,是线程池和进程池, 就是在初始化的时候先定义几个线程,之后让这些线程来处理相应的函数,这样不用每次都需要新创建线程

线程池的基本使用

exector = ThreadPoolExecutor(max_workers=1) # 初始化一个线程池,只有一个线程

exector.submit(fn, args, kwargs) # 将函数submit到线程池中

如果线程池中有n个线程,当提交的task数量大于n时,则多余的task将放到队列中。

再次修改上面的emit函数

exector = ThreadPoolExecutor(max_workers=1)

def emit(self, record):

msg = self.format(record)

timeout = aiohttp.ClientTimeout(total=6)

if self.method == "GET":

if (self.url.find("?") >= 0):

sep = '&'

else:

sep = '?'

url = self.url + "%c%s" % (sep, urllib.parse.urlencode({"log": msg}))

exector.submit(requests.get, url, timeout=6)

else:

headers = {

"Content-type": "application/x-www-form-urlencoded",

"Content-length": str(len(msg))

}

exector.submit(requests.post, self.url, data={'log': msg},

headers=headers, timeout=6)

这里为什么要只初始化一个只有一个线程的线程池? 因为这样的话可以保证先进队列里的日志会先被发 送,如果池子中有多个线程,则不一定保证顺序了。

3

使用异步aiohttp库来发送请求

上面的CustomHandler类中的emit方法使用的是requests.post来发送日志,这个requests本身是阻塞运 行的,也正上由于它的存在,才使得脚本卡了很长时间,所们我们可以将阻塞运行的requests库替换为异步 的aiohttp来执行get和post方法, 重写一个CustomHandler中的emit方法

class CustomHandler(logging.Handler):

def __init__(self, host, uri, method="POST"):

logging.Handler.__init__(self)

self.url = "%s/%s" % (host, uri)

method = method.upper()

if method not in ["GET", "POST"]:

raise ValueError("method must be GET or POST")

self.method = method

async def emit(self, record):

msg = self.format(record)

timeout = aiohttp.ClientTimeout(total=6)

if self.method == "GET":

if (self.url.find("?") >= 0):

sep = '&'

else:

sep = '?'

url = self.url + "%c%s" % (sep, urllib.parse.urlencode({"log":

msg}))

async with aiohttp.ClientSession(timeout=timeout) as session:

async with session.get(self.url) as resp:

print(await resp.text())

else:

headers = {

"Content-type": "application/x-www-form-urlencoded",

"Content-length": str(len(msg))

}

async with aiohttp.ClientSession(timeout=timeout, headers=headers)

as session:

async with session.post(self.url, data={'log': msg}) as resp:

print(await resp.text())

这时代码执行崩溃了

C:\Python37\lib\logging\__init__.py:894: RuntimeWarning: coroutine

'CustomHandler.emit' was never awaited

self.emit(record)

RuntimeWarning: Enable tracemalloc to get the object allocation traceback

服务端也没有收到发送日志的请求。

究其原因是由于emit方法中使用 async with session.post 函数,它需要在一个使用async 修饰的函数 里执行,所以修改emit函数,使用async来修饰,这里emit函数变成了异步的函数, 返回的是一个 coroutine 对象,要想执行coroutine对象,需要使用await, 但是脚本里却没有在哪里调用 await emit() ,所以崩溃信息 中显示 coroutine 'CustomHandler.emit' was never awaited。

既然emit方法返回的是一个coroutine对象,那么我们将它放一个loop中执行

async def main():

await logger.debug("今天天气不错")

await logger.debug("是风和日丽的")

loop = asyncio.get_event_loop()

loop.run_until_complete(main())

执行依然报错

raise TypeError('An asyncio.Future, a coroutine or an awaitable is '

意思是需要的是一个coroutine,但是传进来的对象不是。

这似乎就没有办法了,想要使用异步库来发送,但是却没有可以调用await的地方。

解决办法是有的,我们使用 asyncio.get_event_loop() 获取一个事件循环对象, 我们可以在这个对象上注册很多协程对象,这样当执行事件循环的时候,就是去执行注册在该事件循环上的协程, 我们通过一个小例子来看一下

import asyncio

async def test(n):

while n > 0:

await asyncio.sleep(1)

print("test {}".format(n))

n -= 1

return n

async def test2(n):

while n >0:

await asyncio.sleep(1)

print("test2 {}".format(n))

n -= 1

def stoploop(task):

print("执行结束, task n is {}".format(task.result()))

loop.stop()

loop = asyncio.get_event_loop()

task = loop.create_task(test(5))

task2 = loop.create_task(test2(3))

task.add_done_callback(stoploop)

task2 = loop.create_task(test2(3))

loop.run_forever()

我们使用 loop = asyncio.get_event_loop() 创建了一个事件循环对象loop, 并且在loop上创建了两个task, 并且给task1添加了一个回调函数,在task1它执行结束以后,将loop停掉。

注意看上面的代码,我们并没有在某处使用await来执行协程,而是通过将协程注册到某个事件循环对象上, 然后调用该循环的 run_forever() 函数,从而使该循环上的协程对象得以正常的执行。

上面得到的输出为

test 5

test2 3

test 4

test2 2

test 3

test2 1

test 2

test 1

执行结束, task n is 0

可以看到,使用事件循环对象创建的task,在该循环执行run_forever() 以后就可以执行了如果不执行 loop.run_forever() 函数,则注册在它上面的协程也不会执行

loop = asyncio.get_event_loop()

task = loop.create_task(test(5))

task.add_done_callback(stoploop)

task2 = loop.create_task(test2(3))

time.sleep(5)

# loop.run_forever()

上面的代码将loop.run_forever() 注释掉,换成time.sleep(5) 停5秒, 这时脚本不会有任何输出,在停了5秒 以后就中止了,

回到之前的日志发送远程服务器的代码,我们可以使用aiohttp封装一个发送数据的函数, 然后在emit中将 这个函数注册到全局的事件循环对象loop中,最后再执行loop.run_forever()

loop = asyncio.get_event_loop()

class CustomHandler(logging.Handler):

def __init__(self, host, uri, method="POST"):

logging.Handler.__init__(self)

self.url = "%s/%s" % (host, uri)

method = method.upper()

if method not in ["GET", "POST"]:

raise ValueError("method must be GET or POST")

self.method = method

# 使用aiohttp封装发送数据函数

async def submit(self, data):

timeout = aiohttp.ClientTimeout(total=6)

if self.method == "GET":

if self.url.find("?") >= 0:

sep = '&'

else:

sep = '?'

url = self.url + "%c%s" % (sep, urllib.parse.urlencode({"log":

data}))

async with aiohttp.ClientSession(timeout=timeout) as session:

async with session.get(url) as resp:

print(await resp.text())

else:

headers = {

"Content-type": "application/x-www-form-urlencoded",

}

async with aiohttp.ClientSession(timeout=timeout, headers=headers)

as session:

async with session.post(self.url, data={'log': data}) as resp:

print(await resp.text())

return True

def emit(self, record):

msg = self.format(record)

loop.create_task(self.submit(msg))

# 添加一个httphandler

http_handler = CustomHandler(r"http://127.0.0.1:1987", 'api/log/get')

http_handler.setLevel(logging.DEBUG)

http_handler.setFormatter(fmt)

logger.addHandler(http_handler)

logger.debug("今天天气不错")

logger.debug("是风和日丽的")

loop.run_forever()

时脚本就可以正常的异步执行了

loop.create_task(self.submit(msg)) 也可以使用

asyncio.ensure_future(self.submit(msg), loop=loop) 来代替,目的都是将协程对象注册到事件循环中。

但这种方式有一点要注意,loop.run_forever() 将会一直阻塞,所以需要有个地方调用 loop.stop() 方法. 可以注册到某个task的回调中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值