diff --git a/monkey/monkey_island/cc/server_utils/island_logger.py b/monkey/monkey_island/cc/server_utils/island_logger.py index f8eca8cbb..a512e0217 100644 --- a/monkey/monkey_island/cc/server_utils/island_logger.py +++ b/monkey/monkey_island/cc/server_utils/island_logger.py @@ -1,6 +1,7 @@ import json import logging.config import os +from typing import Dict from monkey_island.cc.consts import DEFAULT_LOGGING_CONFIG_PATH @@ -28,6 +29,17 @@ def json_setup_logging( if os.path.exists(path): with open(path, "rt") as f: config = json.load(f) + _expanduser_log_file_paths(config) logging.config.dictConfig(config) else: logging.basicConfig(level=default_level) + + +def _expanduser_log_file_paths(config: Dict): + handlers = config.get("handlers", {}) + + for handler_settings in handlers.values(): + if "filename" in handler_settings: + handler_settings["filename"] = os.path.expanduser( + handler_settings["filename"] + ) diff --git a/monkey/monkey_island/cc/test_island_logger.py b/monkey/monkey_island/cc/test_island_logger.py new file mode 100644 index 000000000..bd9de46f4 --- /dev/null +++ b/monkey/monkey_island/cc/test_island_logger.py @@ -0,0 +1,29 @@ +import logging +import os + +from monkey_island.cc.consts import MONKEY_ISLAND_ABS_PATH +from monkey_island.cc.island_logger import json_setup_logging + +TEST_LOGGING_CONFIG_PATH = os.path.join(MONKEY_ISLAND_ABS_PATH, "cc", "testing", + "logger_config.json") + + +def set_home_env(monkeypatch, tmpdir): + monkeypatch.setenv("HOME", tmpdir) + + +def test_expanduser_filename(monkeypatch, tmpdir): + INFO_LOG = os.path.join(tmpdir, "info.log") + TEST_STRING = "Hello, Monkey!" + + set_home_env(monkeypatch, tmpdir) + + json_setup_logging(TEST_LOGGING_CONFIG_PATH) + + logger = logging.getLogger("TestLogger") + logger.info(TEST_STRING) + + assert os.path.isfile(INFO_LOG) + with open(INFO_LOG, "r") as f: + line = f.readline() + assert TEST_STRING in line diff --git a/monkey/monkey_island/cc/testing/logger_config.json b/monkey/monkey_island/cc/testing/logger_config.json new file mode 100644 index 000000000..b3ad82641 --- /dev/null +++ b/monkey/monkey_island/cc/testing/logger_config.json @@ -0,0 +1,33 @@ +{ + "version": 1, + "disable_existing_loggers": false, + "formatters": { + "simple": { + "format": "%(asctime)s - %(filename)s:%(lineno)s - %(funcName)10s() - %(levelname)s - %(message)s" + } + }, + "handlers": { + "console": { + "class": "logging.StreamHandler", + "level": "DEBUG", + "formatter": "simple", + "stream": "ext://sys.stdout" + }, + "info_file_handler": { + "class": "logging.handlers.RotatingFileHandler", + "level": "INFO", + "formatter": "simple", + "filename": "~/info.log", + "maxBytes": 10485760, + "backupCount": 20, + "encoding": "utf8" + } + }, + "root": { + "level": "DEBUG", + "handlers": [ + "console", + "info_file_handler" + ] + } +}