Skip to main content
 首页 » 编程设计

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

2024年12月31日11bluestorm

我每晚都使用 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获取更多信息。