在python中使用日志最常用的方式就是在控制台和文件中输出日志了,logging模块也很好的提供的相应的类,使用起来也非常方便,但是有时我们可能会有一些需求,如还需要将日志发送到远端,或者直接写入数据库,这种需求该如何实现呢?

一、StreamHandler和FileHandler

首先我们先来写一套简单输出到cmd和文件中的代码# -*- coding: utf-8 -*-"""

-------------------------------------------------

File Name: loger

Description :

Author : yangyanxing

date: 2020/9/23

-------------------------------------------------

"""import loggingimport sysimport os# 初始化loggerlogger = logging.getLogger("yyx")

logger.setLevel(logging.DEBUG)# 设置日志格式fmt = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')# 添加cmd handlercmd_handler = logging.StreamHandler(sys.stdout)

cmd_handler.setLevel(logging.DEBUG)

cmd_handler.setFormatter(fmt)# 添加文件的handlerlogpath = os.path.join(os.getcwd(), 'debug.log')

file_handler = logging.FileHandler(logpath)

file_handler.setLevel(logging.DEBUG)

file_handler.setFormatter(fmt)# 将cmd和file handler添加到logger中logger.addHandler(cmd_handler)

logger.addHandler(file_handler)

logger.debug("今天天气不错")复制代码

首先初始化一个logger, 并且设置它的日志级别是DEBUG,然后添初始化了 cmd_handler和 file_handler, 最后将它们添加到logger中, 运行脚本,会在cmd中打印出 [2020-09-23 10:45:56] [DEBUG] 今天天气不错 且会写入到当前目录下的debug.log文件中.

二、添加HTTPHandler

如果想要在记录时将日志发送到远程服务器上,可以添加一个 HTTPHandler , 在python标准库logging.handler中,已经为我们定义好了很多handler,有些我们可以直接用,本地使用tornado写一个接收日志的接口,将接收到的参数全都打印出来# 添加一个httphandlerimport logging.handlers

http_handler = logging.handlers.HTTPHandler(r"127.0.0.1:1987", '/api/log/get')

http_handler.setLevel(logging.DEBUG)

http_handler.setFormatter(fmt)

logger.addHandler(http_handler)

logger.debug("今天天气不错")复制代码

结果在服务端我们收到了很多信息{

'name': [b 'yyx'],

'msg': [b '\xe4\xbb\x8a\xe5\xa4\xa9\xe5\xa4\xa9\xe6\xb0\x94\xe4\xb8\x8d\xe9\x94\x99'],

'args': [b '()'],

'levelname': [b 'DEBUG'],

'levelno': [b '10'],

'pathname': [b 'I:/workplace/yangyanxing/test/loger.py'],

'filename': [b 'loger.py'],

'module': [b 'loger'],

'exc_info': [b 'None'],

'exc_text': [b 'None'],

'stack_info': [b 'None'],

'lineno': [b '41'],

'funcName': [b ''],

'created': [b '1600831054.8881223'],

'msecs': [b '888.1223201751709'],

'relativeCreated': [b '22.99976348876953'],

'thread': [b '14876'],

'threadName': [b 'MainThread'],

'processName': [b 'MainProcess'],

'process': [b '8648'],

'message': [b '\xe4\xbb\x8a\xe5\xa4\xa9\xe5\xa4\xa9\xe6\xb0\x94\xe4\xb8\x8d\xe9\x94\x99'],

'asctime': [b '2020-09-23 11:17:34']

}复制代码

可以说是信息非常之多,但是却并不是我们想要的样子,我们只是想要类似于 [2020-09-23 10:45:56] [DEBUG] 今天天气不错 这样的日志.

logging.handlers.HTTPHandler 只是简单的将日志所有信息发送给服务端,至于服务端要怎么组织内容是由服务端来完成. 所以我们可以有两种方法,一种是改服务端代码,根据传过来的日志信息重新组织一下日志内容, 第二种是我们重新写一个类,让它在发送的时候将重新格式化日志内容发送到服务端.

我们采用第二种方法,因为这种方法比较灵活, 服务端只是用于记录,发送什么内容应该是由客户端来决定。

我们需要重新定义一个类,我们可以参考logging.handlers.HTTPHandler 这个类,重新写一个httpHandler类

每个日志类都需要重写emit方法,记录日志时真正要执行是也就是这个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 def emit(self, record):

'''

:param record:

:return:

'''

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}))

requests.get(url, timeout=1) else:

headers = { "Content-type": "application/x-www-form-urlencoded", "Content-length": str(len(msg))

}

requests.post(self.url, data={'log': msg}, headers=headers, timeout=1)复制代码

上面代码中有一行定义发送的参数 msg = self.format(record)

这行代码表示,将会根据日志对象设置的格式返回对应的内容.

之后再将内容通过requests库进行发送,无论使用get 还是post方式,服务端都可以正常的接收到日志

[2020-09-23 11:43:50] [DEBUG] 今天天气不错

三、异步的发送远程日志

现在我们考虑一个问题,当日志发送到远程服务器过程中,如果远程服务器处理的很慢,会耗费一定的时间,那么这时记录日志就会都变慢

修改服务器日志处理类,让其停顿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秒。

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

3.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}, "headers":headers})

t.start()复制代码

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

3.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.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 -= 1def 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))# 添加一个httphandlerhttp_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的回调中.

以上就是一起看看python 中日志异步发送到远程服务器的详细内容,更多请关注php中文网其它相关文章!

本文转载于:juejin,如有侵犯,请联系a@php.cn删除

python processpoolexector 释放内存_一起看看python 中日志异步发送到远程服务器相关推荐

  1. python processpoolexector 释放内存_关于python:如何在multiprocessing.queue中从Process中释放内存?...

    我有一个程序试图预测一周内发送的每封电子邮件的电子邮件转换(因此,通常是7封). 输出是7个不同的文件,每个客户的预测得分. 串行运行这些可能需要8个小时,因此我尝试使用multiprocessing ...

  2. python processpoolexector 释放内存_使用Python的multiprocessing.pool,内存使用量不断增长...

    这是程序: #!/usr/bin/python import multiprocessing def dummy_func(r): pass def worker(): pass if __name_ ...

  3. python读取数据库数据释放内存_在使用python处理数据时,为什么其内存无法自动释放掉?...

    这与Python的内存处理机制有关. 我们对内存一定要合理利用,这是每一个程序员必须的基本功.减少垃圾排放,这才是根本,所以每一个程序员他必须得知道自己用了多少内存.别自己这些内存要不要释放,我为什么 ...

  4. python基于值得内存_为什么说Python采用的是基于值的内存管理模式

    匿名用户 1级 2018-01-31 回答 先从较浅的层面来说,Python的内存管理机制可以从三个方面来讲 (1)垃圾回收 (2)引用计数 (3)内存池机制 一.垃圾回收: python不像C++, ...

  5. python强制释放内存_强制Python释放对象以释放内存

    我运行以下代码:from myUtilities import myObject for year in range(2006,2015): front = 'D:\\newFilings\\' ba ...

  6. python processpoolexector 释放内存_python之ThreadPoolExecutor

    在前面的博客中介绍了线程的用法,每次使用都要创建线程,启动线程,有没有什么办法简单操作呢. python3.2引入的concurrent.future模块中有ThreadPoolExecutor和Pr ...

  7. 如何让python进程常驻内存_常驻内存程序--python+rrd监控cpu

    问题1: A. 编写一个C程序,常驻内存且占用100M的内存. #include #include #include #include #define MAXFILE 65535 #define si ...

  8. python 释放变量所指向的内存_通俗易懂的Python垃圾回收机制及内存管理

    Python垃圾回收机制及内存管理 内存管理: 先定义一个变量 name='wxl' 那么python会在内存中开辟一小块区域存放"wxl",此时变量的值是我们真正想要存储的,wx ...

  9. python 释放内存_学了4年C++后,我转向了Python

    作者 | asya f 编译 | Lisa C++ 已经学不动了,现在换 Python 还来得及吗?一位四年工作经验的 C++ 程序员亲述转型历程,这不仅仅是语言上的转变,而是代码思维甚至工作环境的转 ...

最新文章

  1. CSS3的边框(border)属性-radius
  2. Zookeeper的一次迁移故障
  3. stm32烧不进去程序_STM32的FLASH和SRAM的使用情况分析
  4. OpenCV学习笔记:绘图指令(矩形、圆、线、文本标注)
  5. 黄聪:C#索引器详解、示例
  6. 一句代码实现gzip压缩解压缩
  7. mysql double 存储_关于MYSQL中FLOAT和DOUBLE类型的存储-阿里云开发者社区
  8. MYSQL中日期与字符串间的相互转换
  9. 魔方与科学和计算机表现李世春,科学网—魔方 - 李世春的博文
  10. UnixVi命令详解
  11. 制作逼真立体玻璃奶瓶图片的PS教程
  12. 2021-03-27
  13. C语言编程>第二十四周 ① 请补充fun函数,该函数的功能是判断一个数是否为素数。该数是素数时,函数返回字符串 “yes!”,否则函数返回字符串 “no!”,并在主函数中输出。
  14. bandwagonhost.com (***)机房网速比较
  15. recycler上下拉刷新view
  16. 指针游戏1 最简单的指针游戏
  17. Line推出新语音群聊功能 最多支持200人
  18. JustLaws 法律文库贡献指南
  19. CKEditor插件的使用
  20. 电脑桌面一计算机打不开,idf,教您怎么解决电脑桌面图标打不开

热门文章

  1. Catch a cold, will be back later
  2. 对四象限法则的一点思考
  3. 企业组网为组织带来什么便利性和实用性?—Vecloud微云
  4. P4512 【模板】多项式除法
  5. 【转载】视频CDN技术原理与流程说明
  6. 接口抽象类继承父类和子类
  7. html基本标签结构
  8. spring4-3-AOP-面向切面编程
  9. MVC3中的tempdata,viewdata,viewbag总结
  10. Win2003下Asp配置技巧 http 500内部服务器错误