mpacklog — Log dictionaries to file using MessagePack  v2.1.0
logger.py
Go to the documentation of this file.
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright 2022 Stéphane Caron
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 
18 
19 import asyncio
20 
21 import aiofiles
22 import msgpack
23 
24 from .serialize import serialize
25 
26 
27 class Logger:
28 
29  """!
30  Logger with Asynchronous I/O.
31  """
32 
33  def __init__(self, path):
34  self.__keep_going = True
35  self.path = path
36  self.queue = asyncio.Queue()
37 
38  async def put(self, message):
39  await self.queue.put(message)
40 
41  async def stop(self):
42  self.__keep_going = False
43 
44  async def write(self):
45  file = await aiofiles.open(self.path, "wb")
46  packer = msgpack.Packer(default=serialize, use_bin_type=True)
47  while self.__keep_going:
48  message = await self.queue.get()
49  if message == {"exit": True}:
50  break
51  await file.write(packer.pack(message))
52  # Flushing has little effect when the Python process is configured
53  # more predictable although a little bit lower on average.
54  # on its own core (CPUID). When running on the default core, it
55  # tends to make the slack duration of the other coroutines
56  await file.flush()
57  await file.close()
mpacklog.mpacklog.python.logger.Logger.__keep_going
__keep_going
Definition: logger.py:34
mpacklog.mpacklog.python.logger.Logger
Logger with Asynchronous I/O.
Definition: logger.py:27
mpacklog.mpacklog.python.logger.Logger.path
path
Definition: logger.py:35
mpacklog.mpacklog.python.logger.Logger.queue
queue
Definition: logger.py:36
mpacklog.mpacklog.python.logger.Logger.put
def put(self, message)
Definition: logger.py:38
mpacklog.mpacklog.python.logger.Logger.write
def write(self)
Definition: logger.py:44
mpacklog.mpacklog.python.logger.Logger.__init__
def __init__(self, path)
Definition: logger.py:33
mpacklog.mpacklog.python.logger.Logger.stop
def stop(self)
Definition: logger.py:41