python flask logging 配置后 启动异常 [Errno 13] Permission denied
配置代码:
点击查看代码
def init_log():
# 创建logger对象。传入logger名字
logger = logging.getLogger()
log_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'logs'))
print('log_path:', log_path)
# 设置日志记录等级
logger.setLevel(logging.INFO)
# interval 滚动周期,
# when="MIDNIGHT", interval=1 表示每天0点为更新点,每天生成一个文件
# backupCount 表示日志保存个数
file_handler = TimedRotatingFileHandler(
filename=log_path, when="MIDNIGHT", interval=1, backupCount=30
)
# filename="mylog" suffix设置,会生成文件名为mylog.2020-02-25.log
file_handler.suffix = "%Y-%m-%d.log"
# extMatch是编译好正则表达式,用于匹配日志文件名后缀
# 需要注意的是suffix和extMatch一定要匹配的上,如果不匹配,过期日志不会被删除。
file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}.log$")
# 定义日志输出格式
file_handler.setFormatter(
logging.Formatter(
"[%(asctime)s] [%(process)d] [%(levelname)s] - %(module)s.%(funcName)s (%(filename)s:%(lineno)d) - %(message)s"
)
)
logger.addHandler(file_handler)
异常信息:
Traceback (most recent call last):
File "app.py", line 84, in <module>
init_log()
File "app.py", line 67, in init_log
filename=log_path, when="MIDNIGHT", interval=1, backupCount=30
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\logging\handlers.py", line 200, in __init__
BaseRotatingHandler.__init__(self, filename, 'a', encoding, delay)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\logging\handlers.py", line 55, in __init__
logging.FileHandler.__init__(self, filename, mode, encoding, delay)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\logging\__init__.py", line 1087, in __init__
StreamHandler.__init__(self, self._open())
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\logging\__init__.py", line 1116, in _open
return open(self.baseFilename, self.mode, encoding=self.encoding)
PermissionError: [Errno 13] Permission denied: 'E:\\git_ali\\pytool-httpapi\\logs'
查了很多资料,FQ也没找到相关问题。后来各种试,发现是因为自己手动创建了logs文件夹在项目目录下,而配置时又指定了日志名为logs,导致它创建不出来logs就抛异常了~
抛的这异常也是够不明不白的~~