gpt4 book ai didi

python - 如何用Python3中的logging包把自己的日志文件放到正确的地方?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:15:10 29 4
gpt4 key购买 nike

我想把我自己的应用程序的日志文件放在正确的地方。我不确定,但我认为在 unixoid 系统上它是 /var/log。但是权限有问题。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging, logging.handlers

_LOG_FILENAME = '/var/log/myapp.log'

log = logging.getLogger('')
fh = logging.handlers.RotatingFileHandler(_LOG_FILENAME, maxBytes=10240, backupCount=3)
log.addHandler(fh)

log.info('log message')

导致此错误:

Traceback (most recent call last):
File "./log.py", line 8, in <module>
fh = logging.handlers.RotatingFileHandler(_LOG_FILENAME, maxBytes=10240, backupCount=3)
File "/usr/lib/python3.4/logging/handlers.py", line 150, in __init__
BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)
File "/usr/lib/python3.4/logging/handlers.py", line 57, in __init__
logging.FileHandler.__init__(self, filename, mode, encoding, delay)
File "/usr/lib/python3.4/logging/__init__.py", line 992, in __init__
StreamHandler.__init__(self, self._open())
File "/usr/lib/python3.4/logging/__init__.py", line 1016, in _open
return open(self.baseFilename, self.mode, encoding=self.encoding)
PermissionError: [Errno 13] Permission denied: '/var/log/myapp.log'

最佳答案

默认情况下,要将日志文件放在/var/log 中,您的应用程序必须以根用户身份运行。

提示:创建子目录并设置好属主

 mkdir /var/log/myapp
chown myuser /var/log/myapp

最好的问候

关于python - 如何用Python3中的logging包把自己的日志文件放到正确的地方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31219096/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com