python - 如何使用 Python 的内置日志记录和 Asyncio(权限错误)

标签 python logging websocket python-asyncio

我每晚都使用 TimedRotatingFileHandler 从日志记录到新文件。根据logging docs :

The system will save old log files by appending extensions to the filename.

当这种情况发生时,我得到了一个权限错误:

--- Logging error ---

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\Users\lh\PythonIntegration\Connect\Logs\WS_API_integration_client' -> 'C:\Users\lh\PythonIntegration\Connect\Logs\WS_API_integration_client.2018-10-08_13-00'

我猜这与我有一个运行异步进程的循环有关。但即使我只用一个日志记录事件测试它,我也会收到权限错误。这意味着它试图更改它正在写入的同一文件的扩展名 - 因此出现权限错误。我如何告诉记录器关闭文件,以便它可以将扩展名添加到文件名中?

这是我的client.py

rotating_logger = logging.getLogger('ClientLogger')
rotating_logger.setLevel(logging.DEBUG)
handler = logging.handlers.TimedRotatingFileHandler(
              log_file, when = 'midnight',backupCount=30)              
formatter = logging.Formatter(fmt='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
handler.setFormatter(formatter)
rotating_logger.addHandler(handler)

async def keep_alive(websocket):
    """
    Sends keep-alive message to the server. 
    """
    while websocket.open:            
        await websocket.send('hello')   
        await asyncio.sleep(60*1)

async def open_connection():
    loop = asyncio.get_event_loop()
    with concurrent.futures.ProcessPoolExecutor() as pool:
        async with websockets.connect( 
                'wss://{}:{}@host.net/api/ws'.format(user,pswd), 
                ssl=True, 
                max_queue = 1000) as websocket:
            """
            Keep connection alive.
            """            
            asyncio.ensure_future(keep_alive(websocket))

            """
            Handle messages from server
            """ 
            while True:  
                """
                Handle message from server.
                """
                message = await websocket.recv()
                if message.isdigit():
                    rotating_logger.info ('Keep alive message: {}'.format(str(message)))

if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(open_connection())

最佳答案

我不认为它与 asyncio 有任何关系。您已经启动了多个流程来处理您的工作量。在 Windows 下,一个文件在被另一个进程打开时不能被重命名。通常,即使在 POSIX 下,也不能保证从多个进程写入同一个文件会按预期工作,因为进程没有序列化访问文件的机制。所以答案是有一个单独的工作进程写入文件,其他人通过套接字或 multiprocessing 队列向它传递事件。查看logging cookbook获取更多信息。

关于python - 如何使用 Python 的内置日志记录和 Asyncio(权限错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52708756/

相关文章:

python - 如何为 IPython 小部件设置默认值?

python - 使用 beautifulsoup 在 moneycontrol 网站的搜索框中填写股票输入

python - 为什么从`__iadd__`返回除“self”之外的任何东西?

java - 如何分离Log4j配置?

java - 如何在应用程序执行期间覆盖logging.properties?

javascript - 意外的响应代码 : 200

Spring Boot - websocket Controller 问题

Python Tornado - 异步请求正在阻塞

使用 ptb : Same line logged twice but only one handler added 进行 Python 日志记录

java - 在 Spring Boot 应用程序的 WebSocketConfigurer 中使用 @PathParam(javax.websocket.server.PathParam)