Skip to content

Commit 061260e

Browse files
SammyRamonemergify[bot]
authored andcommitted
add format overriding by environment variables (#722)
* add format overriding by environment variables Signed-off-by: Marc Bestmann <[email protected]> * add test for env var based formatting Signed-off-by: Marc Bestmann <[email protected]> --------- Signed-off-by: Marc Bestmann <[email protected]> (cherry picked from commit 749a6e5)
1 parent f31c1ff commit 061260e

File tree

2 files changed

+51
-4
lines changed

2 files changed

+51
-4
lines changed

launch/launch/logging/__init__.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,10 +180,21 @@ def set_screen_format(self, screen_format, *, screen_style=None):
180180
:param screen_format: format specification used when logging to the screen,
181181
as expected by the `logging.Formatter` constructor.
182182
Alternatively, aliases for common formats are available, see above.
183+
This format can also be overridden by the environment variable
184+
'OVERRIDE_LAUNCH_SCREEN_FORMAT'.
183185
:param screen_style: the screen style used if no alias is used for
184186
screen_format.
185187
No style can be provided if a format alias is given.
186188
"""
189+
# Check if the environment variable is set
190+
screen_format_env = os.environ.get('OVERRIDE_LAUNCH_SCREEN_FORMAT')
191+
# If the environment variable is set override the given format
192+
if screen_format_env not in [None, '']:
193+
# encoded escape characters correctly
194+
screen_format = screen_format_env.encode(
195+
'latin1').decode('unicode_escape')
196+
# Set the style correspondingly
197+
screen_style = '{'
187198
if screen_format is not None:
188199
if screen_format == 'default':
189200
screen_format = '[{levelname}] [{name}]: {msg}'
@@ -232,9 +243,20 @@ def set_log_format(self, log_format, *, log_style=None):
232243
as expected by the `logging.Formatter` constructor.
233244
Alternatively, the 'default' alias can be given to log verbosity level,
234245
logger name and logged message.
246+
This format can also be overridden by the environment variable
247+
'OVERRIDE_LAUNCH_LOG_FORMAT'.
235248
:param log_style: the log style used if no alias is given for log_format.
236249
No style can be provided if a format alias is given.
237250
"""
251+
# Check if the environment variable is set
252+
log_format_env = os.environ.get('OVERRIDE_LAUNCH_LOG_FORMAT')
253+
# If the environment variable is set override the given format
254+
if log_format_env not in [None, '']:
255+
# encoded escape characters correctly
256+
log_format = log_format_env.encode(
257+
'latin1').decode('unicode_escape')
258+
# Set the style correspondingly
259+
log_style = '{'
238260
if log_format is not None:
239261
if log_format == 'default':
240262
log_format = '{created:.7f} [{levelname}] [{name}]: {msg}'

launch/test/launch/test_logging.py

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,13 @@ def log_dir(tmpdir_factory):
3333
return str(tmpdir_factory.mktemp('logs'))
3434

3535

36-
def test_bad_logging_launch_config():
36+
@pytest.fixture
37+
def mock_clean_env(monkeypatch):
38+
monkeypatch.delenv('OVERRIDE_LAUNCH_SCREEN_FORMAT', raising=False)
39+
monkeypatch.delenv('OVERRIDE_LAUNCH_LOG_FORMAT', raising=False)
40+
41+
42+
def test_bad_logging_launch_config(mock_clean_env):
3743
"""Tests that setup throws at bad configuration."""
3844
launch.logging.reset()
3945

@@ -85,7 +91,7 @@ def test_output_loggers_bad_configuration(log_dir):
8591
},
8692
)
8793
])
88-
def test_output_loggers_configuration(capsys, log_dir, config, checks):
94+
def test_output_loggers_configuration(capsys, log_dir, config, checks, mock_clean_env):
8995
checks = {'stdout': set(), 'stderr': set(), 'both': set(), **checks}
9096
launch.logging.reset()
9197
launch.logging.launch_config.log_dir = log_dir
@@ -164,7 +170,7 @@ def test_output_loggers_configuration(capsys, log_dir, config, checks):
164170
assert (not os.path.exists(own_log_path) or 0 == os.stat(own_log_path).st_size)
165171

166172

167-
def test_screen_default_format_with_timestamps(capsys, log_dir):
173+
def test_screen_default_format_with_timestamps(capsys, log_dir, mock_clean_env):
168174
"""Test screen logging when using the default logs format with timestamps."""
169175
launch.logging.reset()
170176
launch.logging.launch_config.level = logging.DEBUG
@@ -183,7 +189,7 @@ def test_screen_default_format_with_timestamps(capsys, log_dir):
183189
assert 0 == len(capture.err)
184190

185191

186-
def test_screen_default_format(capsys):
192+
def test_screen_default_format(capsys, mock_clean_env):
187193
"""Test screen logging when using the default logs format."""
188194
launch.logging.reset()
189195

@@ -220,6 +226,25 @@ def test_log_default_format(log_dir):
220226
assert re.match(r'[0-9]+\.[0-9]+ \[ERROR\] \[some-proc\]: baz', lines[0]) is not None
221227

222228

229+
def test_logging_env_var_format(capsys, monkeypatch):
230+
monkeypatch.setenv('OVERRIDE_LAUNCH_SCREEN_FORMAT', 'TESTSCREEN {message} {name} TESTSCREEN')
231+
monkeypatch.setenv('OVERRIDE_LAUNCH_LOG_FORMAT', 'TESTLOG {message} {name} TESTLOG')
232+
launch.logging.reset()
233+
234+
logger = launch.logging.get_logger('some-proc')
235+
logger.addHandler(launch.logging.launch_config.get_screen_handler())
236+
237+
logger.info('bar')
238+
capture = capsys.readouterr()
239+
lines = capture.out.splitlines()
240+
assert 'TESTSCREEN bar some-proc TESTSCREEN' == lines.pop()
241+
242+
launch.logging.launch_config.get_log_file_handler().flush()
243+
with open(launch.logging.launch_config.get_log_file_path(), 'r') as f:
244+
lines = f.readlines()
245+
assert 'TESTLOG bar some-proc TESTLOG\n' == lines[0]
246+
247+
223248
def test_log_handler_factory(log_dir):
224249
"""Test logging using a custom log handlers."""
225250
class TestStreamHandler(launch.logging.handlers.Handler):

0 commit comments

Comments
 (0)