feat: add user friendly message on permission error

This commit is contained in:
Meng Xiangzhuo
2024-10-25 00:01:41 +08:00
parent ba780276a2
commit 87c8e85068
2 changed files with 40 additions and 6 deletions

View File

@@ -1,4 +1,5 @@
import logging import logging
import sys
from logging import Formatter from logging import Formatter
from logging.handlers import RotatingFileHandler, SysLogHandler from logging.handlers import RotatingFileHandler, SysLogHandler
from pathlib import Path from pathlib import Path
@@ -84,15 +85,27 @@ def setup_logging(config: Config) -> None:
handler_jd.setFormatter(Formatter("%(name)s - %(levelname)s - %(message)s")) handler_jd.setFormatter(Formatter("%(name)s - %(levelname)s - %(message)s"))
logging.root.addHandler(handler_jd) logging.root.addHandler(handler_jd)
else: else:
Path(logfile).parent.mkdir(parents=True, exist_ok=True)
handler_rf = get_existing_handlers(RotatingFileHandler) handler_rf = get_existing_handlers(RotatingFileHandler)
if handler_rf: if handler_rf:
logging.root.removeHandler(handler_rf) logging.root.removeHandler(handler_rf)
handler_rf = RotatingFileHandler( try:
logfile, logfile_path = Path(logfile)
maxBytes=1024 * 1024 * 10, # 10Mb logfile_path.parent.mkdir(parents=True, exist_ok=True)
backupCount=10, handler_rf = RotatingFileHandler(
) logfile_path,
maxBytes=1024 * 1024 * 10, # 10Mb
backupCount=10,
)
except PermissionError:
logger.error(
f'Failed to create or access log file "{logfile_path.absolute()}". '
"Please make sure you have the write permission to the log file or its parent "
"directories. If you're running freqtrade using docker, you see this error "
"message probably because you've logged in as the root user, please switch to "
"non-root user, delete and recreate the directories you need, and then try "
"again."
)
sys.exit(1)
handler_rf.setFormatter(Formatter(LOGFORMAT)) handler_rf.setFormatter(Formatter(LOGFORMAT))
logging.root.addHandler(handler_rf) logging.root.addHandler(handler_rf)

View File

@@ -107,6 +107,27 @@ def test_set_loggers_Filehandler(tmp_path):
logger.handlers = orig_handlers logger.handlers = orig_handlers
@pytest.mark.skipif(sys.platform == "win32", reason="does not run on windows")
def test_set_loggers_Filehandler_without_permission(tmp_path):
logger = logging.getLogger()
orig_handlers = logger.handlers
logger.handlers = []
tmp_path.chmod(0o400)
logfile = tmp_path / "logs/ft_logfile.log"
config = {
"verbosity": 2,
"logfile": str(logfile),
}
setup_logging_pre()
with pytest.raises(SystemExit) as excinfo:
setup_logging(config)
assert excinfo.value.code == 1
logger.handlers = orig_handlers
@pytest.mark.skip(reason="systemd is not installed on every system, so we're not testing this.") @pytest.mark.skip(reason="systemd is not installed on every system, so we're not testing this.")
def test_set_loggers_journald(mocker): def test_set_loggers_journald(mocker):
logger = logging.getLogger() logger = logging.getLogger()