Merge pull request #3996 from freqtrade/fix/doublelog

Fix/doublelog
This commit is contained in:
Matthias 2020-11-25 15:22:37 +01:00 committed by GitHub
commit 7f621416a1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 48 additions and 4 deletions

View File

@ -37,6 +37,13 @@ def _set_loggers(verbosity: int = 0, api_verbosity: str = 'info') -> None:
) )
def get_existing_handlers(handlertype):
"""
Returns Existing handler or None (if the handler has not yet been added to the root handlers).
"""
return next((h for h in logging.root.handlers if isinstance(h, handlertype)), None)
def setup_logging_pre() -> None: def setup_logging_pre() -> None:
""" """
Early setup for logging. Early setup for logging.
@ -71,18 +78,24 @@ def setup_logging(config: Dict[str, Any]) -> None:
# config['logfilename']), which defaults to '/dev/log', applicable for most # config['logfilename']), which defaults to '/dev/log', applicable for most
# of the systems. # of the systems.
address = (s[1], int(s[2])) if len(s) > 2 else s[1] if len(s) > 1 else '/dev/log' address = (s[1], int(s[2])) if len(s) > 2 else s[1] if len(s) > 1 else '/dev/log'
handler = SysLogHandler(address=address) handler_sl = get_existing_handlers(SysLogHandler)
if handler_sl:
logging.root.removeHandler(handler_sl)
handler_sl = SysLogHandler(address=address)
# No datetime field for logging into syslog, to allow syslog # No datetime field for logging into syslog, to allow syslog
# to perform reduction of repeating messages if this is set in the # to perform reduction of repeating messages if this is set in the
# syslog config. The messages should be equal for this. # syslog config. The messages should be equal for this.
handler.setFormatter(Formatter('%(name)s - %(levelname)s - %(message)s')) handler_sl.setFormatter(Formatter('%(name)s - %(levelname)s - %(message)s'))
logging.root.addHandler(handler) logging.root.addHandler(handler_sl)
elif s[0] == 'journald': elif s[0] == 'journald':
try: try:
from systemd.journal import JournaldLogHandler from systemd.journal import JournaldLogHandler
except ImportError: except ImportError:
raise OperationalException("You need the systemd python package be installed in " raise OperationalException("You need the systemd python package be installed in "
"order to use logging to journald.") "order to use logging to journald.")
handler_jd = get_existing_handlers(JournaldLogHandler)
if handler_jd:
logging.root.removeHandler(handler_jd)
handler_jd = JournaldLogHandler() handler_jd = JournaldLogHandler()
# No datetime field for logging into journald, to allow syslog # No datetime field for logging into journald, to allow syslog
# to perform reduction of repeating messages if this is set in the # to perform reduction of repeating messages if this is set in the
@ -90,6 +103,9 @@ def setup_logging(config: Dict[str, Any]) -> 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:
handler_rf = get_existing_handlers(RotatingFileHandler)
if handler_rf:
logging.root.removeHandler(handler_rf)
handler_rf = RotatingFileHandler(logfile, handler_rf = RotatingFileHandler(logfile,
maxBytes=1024 * 1024 * 10, # 10Mb maxBytes=1024 * 1024 * 10, # 10Mb
backupCount=10) backupCount=10)

View File

@ -663,7 +663,7 @@ def test_set_loggers() -> None:
@pytest.mark.skipif(sys.platform == "win32", reason="does not run on windows") @pytest.mark.skipif(sys.platform == "win32", reason="does not run on windows")
def test_set_loggers_syslog(mocker): def test_set_loggers_syslog():
logger = logging.getLogger() logger = logging.getLogger()
orig_handlers = logger.handlers orig_handlers = logger.handlers
logger.handlers = [] logger.handlers = []
@ -678,10 +678,38 @@ def test_set_loggers_syslog(mocker):
assert [x for x in logger.handlers if type(x) == logging.handlers.SysLogHandler] assert [x for x in logger.handlers if type(x) == logging.handlers.SysLogHandler]
assert [x for x in logger.handlers if type(x) == logging.StreamHandler] assert [x for x in logger.handlers if type(x) == logging.StreamHandler]
assert [x for x in logger.handlers if type(x) == logging.handlers.BufferingHandler] assert [x for x in logger.handlers if type(x) == logging.handlers.BufferingHandler]
# setting up logging again should NOT cause the loggers to be added a second time.
setup_logging(config)
assert len(logger.handlers) == 3
# reset handlers to not break pytest # reset handlers to not break pytest
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(tmpdir):
logger = logging.getLogger()
orig_handlers = logger.handlers
logger.handlers = []
logfile = Path(tmpdir) / 'ft_logfile.log'
config = {'verbosity': 2,
'logfile': str(logfile),
}
setup_logging_pre()
setup_logging(config)
assert len(logger.handlers) == 3
assert [x for x in logger.handlers if type(x) == logging.handlers.RotatingFileHandler]
assert [x for x in logger.handlers if type(x) == logging.StreamHandler]
assert [x for x in logger.handlers if type(x) == logging.handlers.BufferingHandler]
# setting up logging again should NOT cause the loggers to be added a second time.
setup_logging(config)
assert len(logger.handlers) == 3
# reset handlers to not break pytest
if logfile.exists:
logfile.unlink()
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()