loguru icon indicating copy to clipboard operation
loguru copied to clipboard

always got PermissionError on window

Open w-Bro opened this issue 2 years ago • 0 comments

1. problem description

i am building a fastapi project and i use loguru as my log util, but i found that, every day i start my project, i got a PermissionError exception about loguru. I know it is because of loguru tried to split the log of last day while loguru can't read it at the same time. I found it work well on unix but window not.It can be solved by deleting the folder of logs and same problem appears on the next day.

2. error message

INFO:     Application startup complete.
--- Logging error in Loguru Handler #1 ---
Record was: {'elapsed': datetime.timedelta(microseconds=401489), 'exception': None, 'extra': {}, 'file': (name='server.py', path='D:\\xxx\backend\\core\\server.py'), 'function': 'init_connect', 'level': (name='INFO', no=20, icon='ℹ️'), 'line': 304, 'message': 'App startup event', 'module': 'server', 'name': 'core.server', 'process': (id=19652, name='SpawnProcess-1'), 'thread': (id=11072, name='MainThread'), 'time': datetime(2021, 12, 7, 11, 54, 47, 294758, tzinfo=datetime.timezone(datetime.timedelta(seconds=28800), 'Öйú±ê׼ʱ¼ä'))}
Traceback (most recent call last):
  File "D:\Miniconda3\envs\fastapi-py37\lib\site-packages\loguru\_handler.py", line 287, in _queued_writer
    self._sink.write(message)
  File "D:\Miniconda3\envs\fastapi-py37\lib\site-packages\loguru\_file_sink.py", line 174, in write
    self._terminate_file(is_rotating=True)
  File "D:\Miniconda3\envs\fastapi-py37\lib\site-packages\loguru\_file_sink.py", line 205, in _terminate_file
    os.rename(old_path, renamed_path)
PermissionError: [WinError 32] 另一个程序正在使用此文件,进程无法访问。: 'D:\\xxx\backend\\logs\\openapi.log' -> 'D:\\xxx\\backend\\logs\\openapi.2021-12-06_12-16-06_650064.log'
--- End of logging error ---

3. python code

import os

from loguru import logger

from config import settings

# 定位到log日志文件
log_path = os.path.join(settings.BASE_PATH, "logs")

if not os.path.exists(log_path):
    os.mkdir(log_path)

# 日志格式
log_formatter = "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level}</level> | " \
                "process[{process}]-thread[{thread}] |<cyan>{name}</cyan>:<cyan>{function}</cyan>:" \
                "<cyan>{line}</cyan> - <level>{message}</level>"


log_path_info = os.path.join(log_path, "openapi.log")

logger.add(log_path_info, format=log_formatter, rotation="00:00", encoding="utf-8", enqueue=True, level="INFO")

w-Bro avatar Dec 07 '21 04:12 w-Bro