/
test_log.py
1776 lines (1494 loc) · 67.5 KB
/
test_log.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Copyright (c) 2011 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from contextlib import contextmanager
import copy
import datetime
import logging
import os
import platform
import shutil
import sys
try:
import syslog
except ImportError:
syslog = None
import tempfile
import time
from dateutil import tz
import mock
from oslo_config import cfg
from oslo_config import fixture as fixture_config # noqa
from oslo_context import context
from oslo_context import fixture as fixture_context
from oslo_i18n import fixture as fixture_trans
from oslo_serialization import jsonutils
from oslotest import base as test_base
import six
import testtools
from oslo_log import _options
from oslo_log import formatters
from oslo_log import handlers
from oslo_log import log
MIN_LOG_INI = b"""[loggers]
keys=root
[formatters]
keys=
[handlers]
keys=
[logger_root]
handlers=
"""
def _fake_context():
ctxt = context.RequestContext(1, 1, overwrite=True)
ctxt.user = 'myuser'
ctxt.tenant = 'mytenant'
ctxt.domain = 'mydomain'
ctxt.project_domain = 'myprojectdomain'
ctxt.user_domain = 'myuserdomain'
return ctxt
def _fake_new_context():
# New style contexts have a user_name / project_name, this is done
# distinctly from the above context to not have to rewrite all the
# other tests.
ctxt = context.RequestContext(1, 1, overwrite=True)
ctxt.user_name = 'myuser'
ctxt.project_name = 'mytenant'
ctxt.domain = 'mydomain'
ctxt.project_domain = 'myprojectdomain'
ctxt.user_domain = 'myuserdomain'
return ctxt
class CommonLoggerTestsMixIn(object):
"""These tests are shared between LoggerTestCase and
LazyLoggerTestCase.
"""
def setUp(self):
super(CommonLoggerTestsMixIn, self).setUp()
# common context has different fields to the defaults in log.py
self.config_fixture = self.useFixture(
fixture_config.Config(cfg.ConfigOpts()))
self.config = self.config_fixture.config
self.CONF = self.config_fixture.conf
log.register_options(self.config_fixture.conf)
self.config(logging_context_format_string='%(asctime)s %(levelname)s '
'%(name)s [%(request_id)s '
'%(user)s %(tenant)s] '
'%(message)s')
self.log = None
log._setup_logging_from_conf(self.config_fixture.conf, 'test', 'test')
def test_handlers_have_context_formatter(self):
formatters_list = []
for h in self.log.logger.handlers:
f = h.formatter
if isinstance(f, formatters.ContextFormatter):
formatters_list.append(f)
self.assertTrue(formatters_list)
self.assertEqual(len(formatters_list), len(self.log.logger.handlers))
def test_handles_context_kwarg(self):
self.log.info("foo", context=_fake_context())
self.assertTrue(True) # didn't raise exception
def test_will_be_debug_if_debug_flag_set(self):
self.config(debug=True)
logger_name = 'test_is_debug'
log.setup(self.CONF, logger_name)
logger = logging.getLogger(logger_name)
self.assertEqual(logging.DEBUG, logger.getEffectiveLevel())
def test_will_be_info_if_debug_flag_not_set(self):
self.config(debug=False)
logger_name = 'test_is_not_debug'
log.setup(self.CONF, logger_name)
logger = logging.getLogger(logger_name)
self.assertEqual(logging.INFO, logger.getEffectiveLevel())
def test_no_logging_via_module(self):
for func in ('critical', 'error', 'exception', 'warning', 'warn',
'info', 'debug', 'log'):
self.assertRaises(AttributeError, getattr, log, func)
class LoggerTestCase(CommonLoggerTestsMixIn, test_base.BaseTestCase):
def setUp(self):
super(LoggerTestCase, self).setUp()
self.log = log.getLogger(None)
class BaseTestCase(test_base.BaseTestCase):
def setUp(self):
super(BaseTestCase, self).setUp()
self.context_fixture = self.useFixture(
fixture_context.ClearRequestContext())
self.config_fixture = self.useFixture(
fixture_config.Config(cfg.ConfigOpts()))
self.config = self.config_fixture.config
self.CONF = self.config_fixture.conf
log.register_options(self.CONF)
log.setup(self.CONF, 'base')
class LogTestBase(BaseTestCase):
"""Base test class that provides some convenience functions."""
def _add_handler_with_cleanup(self, log_instance, handler=None,
formatter=None):
"""Add a log handler to a log instance.
This function should be used to add handlers to loggers in test cases
instead of directly adding them to ensure that the handler is
correctly removed at the end of the test. Otherwise the handler may
be left on the logger and interfere with subsequent tests.
:param log_instance: The log instance to which the handler will be
added.
:param handler: The handler class to be added. Must be the class
itself, not an instance.
:param formatter: The formatter class to set on the handler. Must be
the class itself, not an instance.
"""
self.stream = six.StringIO()
if handler is None:
handler = logging.StreamHandler
self.handler = handler(self.stream)
if formatter is None:
formatter = formatters.ContextFormatter
self.handler.setFormatter(formatter())
log_instance.logger.addHandler(self.handler)
self.addCleanup(log_instance.logger.removeHandler, self.handler)
def _set_log_level_with_cleanup(self, log_instance, level):
"""Set the log level of a logger for the duration of a test.
Use this function to set the log level of a logger and add the
necessary cleanup to reset it back to default at the end of the test.
:param log_instance: The logger whose level will be changed.
:param level: The new log level to use.
"""
self.level = log_instance.logger.getEffectiveLevel()
log_instance.logger.setLevel(level)
self.addCleanup(log_instance.logger.setLevel, self.level)
class LogHandlerTestCase(BaseTestCase):
def test_log_path_logdir(self):
path = os.path.join('some', 'path')
binary = 'foo-bar'
expected = os.path.join(path, '%s.log' % binary)
self.config(log_dir=path, log_file=None)
self.assertEqual(log._get_log_file_path(self.config_fixture.conf,
binary=binary),
expected)
def test_log_path_logfile(self):
path = os.path.join('some', 'path')
binary = 'foo-bar'
expected = os.path.join(path, '%s.log' % binary)
self.config(log_file=expected)
self.assertEqual(log._get_log_file_path(self.config_fixture.conf,
binary=binary),
expected)
def test_log_path_none(self):
prefix = 'foo-bar'
self.config(log_dir=None, log_file=None)
self.assertIsNone(log._get_log_file_path(self.config_fixture.conf,
binary=prefix))
def test_log_path_logfile_overrides_logdir(self):
path = os.path.join(os.sep, 'some', 'path')
prefix = 'foo-bar'
expected = os.path.join(path, '%s.log' % prefix)
self.config(log_dir=os.path.join('some', 'other', 'path'),
log_file=expected)
self.assertEqual(log._get_log_file_path(self.config_fixture.conf,
binary=prefix),
expected)
def test_iter_loggers(self):
mylog = logging.getLogger("abc.cde")
loggers = list(log._iter_loggers())
self.assertIn(logging.getLogger(), loggers)
self.assertIn(mylog, loggers)
class SysLogHandlersTestCase(BaseTestCase):
"""Test the standard Syslog handler."""
def setUp(self):
super(SysLogHandlersTestCase, self).setUp()
self.facility = logging.handlers.SysLogHandler.LOG_USER
self.logger = logging.handlers.SysLogHandler(facility=self.facility)
def test_standard_format(self):
"""Ensure syslog msg isn't modified for standard handler."""
logrecord = logging.LogRecord('name', logging.WARNING, '/tmp', 1,
'Message', None, None)
expected = logrecord
self.assertEqual(expected.getMessage(),
self.logger.format(logrecord))
@testtools.skipUnless(syslog, "syslog is not available")
class OSSysLogHandlerTestCase(BaseTestCase):
def test_handler(self):
handler = handlers.OSSysLogHandler()
syslog.syslog = mock.Mock()
handler.emit(
logging.LogRecord("foo", logging.INFO,
"path", 123, "hey!",
None, None))
self.assertTrue(syslog.syslog.called)
def test_syslog_binary_name(self):
# There is no way to test the actual output written to the
# syslog (e.g. /var/log/syslog) to confirm binary_name value
# is actually present
syslog.openlog = mock.Mock()
handlers.OSSysLogHandler()
syslog.openlog.assert_called_with(handlers._get_binary_name(),
0, syslog.LOG_USER)
def test_find_facility(self):
self.assertEqual(syslog.LOG_USER, log._find_facility("user"))
self.assertEqual(syslog.LOG_LPR, log._find_facility("LPR"))
self.assertEqual(syslog.LOG_LOCAL3, log._find_facility("log_local3"))
self.assertEqual(syslog.LOG_UUCP, log._find_facility("LOG_UUCP"))
self.assertRaises(TypeError,
log._find_facility,
"fougere")
def test_syslog(self):
msg_unicode = u"Benoît Knecht & François Deppierraz login failure"
msg_utf8 = msg_unicode.encode('utf-8')
handler = handlers.OSSysLogHandler()
syslog.syslog = mock.Mock()
handler.emit(
logging.LogRecord("name", logging.INFO, "path", 123,
msg_unicode, None, None))
if six.PY2:
syslog.syslog.assert_called_once_with(syslog.LOG_INFO, msg_utf8)
else:
syslog.syslog.assert_called_once_with(syslog.LOG_INFO, msg_unicode)
class OSJournalHandlerTestCase(BaseTestCase):
"""Test systemd journal logging.
This is a lightweight test for testing systemd journal logging. It
mocks out the journal interface itself, which allows us to not
have to have systemd-python installed (which is not possible to
install on non Linux environments).
Real world testing is also encouraged.
"""
def setUp(self):
super(OSJournalHandlerTestCase, self).setUp()
self.config(use_journal=True)
self.journal = mock.patch("oslo_log.handlers.journal").start()
self.addCleanup(self.journal.stop)
log.setup(self.CONF, 'testing')
def test_emit(self):
l = log.getLogger('nova-test.foo')
local_context = _fake_new_context()
l.info("Foo", context=local_context)
self.assertEqual(
self.journal.send.call_args,
mock.call(mock.ANY, CODE_FILE=mock.ANY, CODE_FUNC='test_emit',
CODE_LINE=mock.ANY, LOGGER_LEVEL='INFO',
LOGGER_NAME='nova-test.foo', PRIORITY=6,
SYSLOG_IDENTIFIER=mock.ANY,
REQUEST_ID=mock.ANY,
PROJECT_NAME='mytenant',
PROCESS_NAME='MainProcess',
THREAD_NAME='MainThread',
USER_NAME='myuser'))
def test_emit_exception(self):
l = log.getLogger('nova-exception.foo')
local_context = _fake_new_context()
try:
raise Exception("Some exception")
except Exception:
l.exception("Foo", context=local_context)
self.assertEqual(
self.journal.send.call_args,
mock.call(mock.ANY, CODE_FILE=mock.ANY,
CODE_FUNC='test_emit_exception',
CODE_LINE=mock.ANY, LOGGER_LEVEL='ERROR',
LOGGER_NAME='nova-exception.foo', PRIORITY=3,
SYSLOG_IDENTIFIER=mock.ANY,
REQUEST_ID=mock.ANY,
EXCEPTION_INFO=mock.ANY,
EXCEPTION_TEXT=mock.ANY,
PROJECT_NAME='mytenant',
PROCESS_NAME='MainProcess',
THREAD_NAME='MainThread',
USER_NAME='myuser'))
class LogLevelTestCase(BaseTestCase):
def setUp(self):
super(LogLevelTestCase, self).setUp()
levels = self.CONF.default_log_levels
info_level = 'nova-test'
warn_level = 'nova-not-debug'
other_level = 'nova-below-debug'
trace_level = 'nova-trace'
levels.append(info_level + '=INFO')
levels.append(warn_level + '=WARN')
levels.append(other_level + '=7')
levels.append(trace_level + '=TRACE')
self.config(default_log_levels=levels)
log.setup(self.CONF, 'testing')
self.log = log.getLogger(info_level)
self.log_no_debug = log.getLogger(warn_level)
self.log_below_debug = log.getLogger(other_level)
self.log_trace = log.getLogger(trace_level)
def test_is_enabled_for(self):
self.assertTrue(self.log.isEnabledFor(logging.INFO))
self.assertFalse(self.log_no_debug.isEnabledFor(logging.DEBUG))
self.assertTrue(self.log_below_debug.isEnabledFor(logging.DEBUG))
self.assertTrue(self.log_below_debug.isEnabledFor(7))
self.assertTrue(self.log_trace.isEnabledFor(log.TRACE))
def test_has_level_from_flags(self):
self.assertEqual(logging.INFO, self.log.logger.getEffectiveLevel())
def test_has_level_from_flags_for_trace(self):
self.assertEqual(log.TRACE, self.log_trace.logger.getEffectiveLevel())
def test_child_log_has_level_of_parent_flag(self):
l = log.getLogger('nova-test.foo')
self.assertEqual(logging.INFO, l.logger.getEffectiveLevel())
def test_child_log_has_level_of_parent_flag_for_trace(self):
l = log.getLogger('nova-trace.foo')
self.assertEqual(log.TRACE, l.logger.getEffectiveLevel())
def test_get_loggers(self):
log._loggers['sentinel_log'] = mock.sentinel.sentinel_log
res = log.get_loggers()
self.assertDictEqual(log._loggers, res)
class JSONFormatterTestCase(LogTestBase):
def setUp(self):
super(JSONFormatterTestCase, self).setUp()
self.log = log.getLogger('test-json')
self._add_handler_with_cleanup(self.log,
formatter=formatters.JSONFormatter)
self._set_log_level_with_cleanup(self.log, logging.DEBUG)
def test_json(self):
test_msg = 'This is a %(test)s line'
test_data = {'test': 'log'}
local_context = _fake_context()
self.log.debug(test_msg, test_data, key='value', context=local_context)
data = jsonutils.loads(self.stream.getvalue())
self.assertTrue(data)
self.assertIn('extra', data)
extra = data['extra']
self.assertEqual('value', extra['key'])
self.assertEqual(local_context.auth_token, extra['auth_token'])
self.assertEqual(local_context.user, extra['user'])
self.assertEqual('test-json', data['name'])
self.assertEqual(test_msg % test_data, data['message'])
self.assertEqual(test_msg, data['msg'])
self.assertEqual(test_data, data['args'])
self.assertEqual('test_log.py', data['filename'])
self.assertEqual('test_json', data['funcname'])
self.assertEqual('DEBUG', data['levelname'])
self.assertEqual(logging.DEBUG, data['levelno'])
self.assertFalse(data['traceback'])
def test_json_exception(self):
test_msg = 'This is %s'
test_data = 'exceptional'
try:
raise Exception('This is exceptional')
except Exception:
self.log.exception(test_msg, test_data)
data = jsonutils.loads(self.stream.getvalue())
self.assertTrue(data)
self.assertIn('extra', data)
self.assertEqual('test-json', data['name'])
self.assertEqual(test_msg % test_data, data['message'])
self.assertEqual(test_msg, data['msg'])
self.assertEqual([test_data], data['args'])
self.assertEqual('ERROR', data['levelname'])
self.assertEqual(logging.ERROR, data['levelno'])
self.assertTrue(data['traceback'])
def test_json_with_extra(self):
test_msg = 'This is a %(test)s line'
test_data = {'test': 'log'}
extra_data = {'special_user': 'user1',
'special_tenant': 'unicorns'}
self.log.debug(test_msg, test_data, key='value', extra=extra_data)
data = jsonutils.loads(self.stream.getvalue())
self.assertTrue(data)
self.assertIn('extra', data)
for k, v in extra_data.items():
self.assertIn(k, data['extra'])
self.assertEqual(v, data['extra'][k])
def test_json_with_extra_keys(self):
test_msg = 'This is a %(test)s line'
test_data = {'test': 'log'}
extra_keys = ['special_tenant', 'special_user']
special_tenant = 'unicorns'
special_user = 'user2'
self.log.debug(test_msg, test_data, key='value',
extra_keys=extra_keys, special_tenant=special_tenant,
special_user=special_user)
data = jsonutils.loads(self.stream.getvalue())
self.assertTrue(data)
self.assertIn('extra', data)
self.assertIn(extra_keys[0], data['extra'])
self.assertEqual(special_tenant, data['extra'][extra_keys[0]])
self.assertIn(extra_keys[1], data['extra'])
self.assertEqual(special_user, data['extra'][extra_keys[1]])
def test_can_process_strings(self):
expected = b'\\u2622'
if six.PY3:
# see ContextFormatterTestCase.test_can_process_strings
expected = '\\\\xe2\\\\x98\\\\xa2'
self.log.info(b'%s', u'\u2622'.encode('utf8'))
self.assertIn(expected, self.stream.getvalue())
def test_exception(self):
ctxt = _fake_context()
ctxt.request_id = six.text_type('99')
try:
raise RuntimeError('test_exception')
except RuntimeError:
self.log.warning('testing', context=ctxt)
data = jsonutils.loads(self.stream.getvalue())
self.assertIn('error_summary', data)
self.assertEqual('RuntimeError: test_exception',
data['error_summary'])
def test_no_exception(self):
ctxt = _fake_context()
ctxt.request_id = six.text_type('99')
self.log.info('testing', context=ctxt)
data = jsonutils.loads(self.stream.getvalue())
self.assertIn('error_summary', data)
self.assertEqual('', data['error_summary'])
def get_fake_datetime(retval):
class FakeDateTime(datetime.datetime):
@classmethod
def fromtimestamp(cls, timestamp):
return retval
return FakeDateTime
class DictStreamHandler(logging.StreamHandler):
"""Serialize dict in order to avoid TypeError in python 3. It is needed for
FluentFormatterTestCase.
"""
def emit(self, record):
try:
msg = self.format(record)
jsonutils.dump(msg, self.stream)
self.stream.flush()
except AttributeError:
self.handleError(record)
class FluentFormatterTestCase(LogTestBase):
def setUp(self):
super(FluentFormatterTestCase, self).setUp()
self.log = log.getLogger('test-fluent')
self._add_handler_with_cleanup(self.log,
handler=DictStreamHandler,
formatter=formatters.FluentFormatter)
self._set_log_level_with_cleanup(self.log, logging.DEBUG)
def test_fluent(self):
test_msg = 'This is a %(test)s line'
test_data = {'test': 'log'}
local_context = _fake_context()
self.log.debug(test_msg, test_data, key='value', context=local_context)
data = jsonutils.loads(self.stream.getvalue())
self.assertIn('lineno', data)
self.assertIn('extra', data)
extra = data['extra']
self.assertEqual('value', extra['key'])
self.assertEqual(local_context.auth_token, extra['auth_token'])
self.assertEqual(local_context.user, extra['user'])
self.assertEqual('test-fluent', data['name'])
self.assertEqual(test_msg % test_data, data['message'])
self.assertEqual('test_log.py', data['filename'])
self.assertEqual('test_fluent', data['funcname'])
self.assertEqual('DEBUG', data['level'])
self.assertFalse(data['traceback'])
def test_exception(self):
local_context = _fake_context()
try:
raise RuntimeError('test_exception')
except RuntimeError:
self.log.warning('testing', context=local_context)
data = jsonutils.loads(self.stream.getvalue())
self.assertIn('error_summary', data)
self.assertEqual('RuntimeError: test_exception',
data['error_summary'])
def test_no_exception(self):
local_context = _fake_context()
self.log.info('testing', context=local_context)
data = jsonutils.loads(self.stream.getvalue())
self.assertIn('error_summary', data)
self.assertEqual('', data['error_summary'])
def test_json_exception(self):
test_msg = 'This is %s'
test_data = 'exceptional'
try:
raise Exception('This is exceptional')
except Exception:
self.log.exception(test_msg, test_data)
data = jsonutils.loads(self.stream.getvalue())
self.assertTrue(data)
self.assertIn('extra', data)
self.assertEqual('test-fluent', data['name'])
self.assertEqual(test_msg % test_data, data['message'])
self.assertEqual('ERROR', data['level'])
self.assertTrue(data['traceback'])
class ContextFormatterTestCase(LogTestBase):
def setUp(self):
super(ContextFormatterTestCase, self).setUp()
self.config(logging_context_format_string="HAS CONTEXT "
"[%(request_id)s]: "
"%(message)s",
logging_default_format_string="NOCTXT: %(message)s",
logging_debug_format_suffix="--DBG")
self.log = log.getLogger('') # obtain root logger instead of 'unknown'
self._add_handler_with_cleanup(self.log)
self._set_log_level_with_cleanup(self.log, logging.DEBUG)
self.trans_fixture = self.useFixture(fixture_trans.Translation())
def test_uncontextualized_log(self):
message = 'foo'
self.log.info(message)
self.assertEqual("NOCTXT: %s\n" % message, self.stream.getvalue())
def test_contextualized_log(self):
ctxt = _fake_context()
message = 'bar'
self.log.info(message, context=ctxt)
expected = 'HAS CONTEXT [%s]: %s\n' % (ctxt.request_id, message)
self.assertEqual(expected, self.stream.getvalue())
def test_context_is_taken_from_tls_variable(self):
ctxt = _fake_context()
message = 'bar'
self.log.info(message)
expected = "HAS CONTEXT [%s]: %s\n" % (ctxt.request_id, message)
self.assertEqual(expected, self.stream.getvalue())
def test_contextual_information_is_imparted_to_3rd_party_log_records(self):
ctxt = _fake_context()
sa_log = logging.getLogger('sqlalchemy.engine')
sa_log.setLevel(logging.INFO)
message = 'emulate logging within sqlalchemy'
sa_log.info(message)
expected = ('HAS CONTEXT [%s]: %s\n' % (ctxt.request_id, message))
self.assertEqual(expected, self.stream.getvalue())
def test_message_logging_3rd_party_log_records(self):
ctxt = _fake_context()
ctxt.request_id = six.text_type('99')
sa_log = logging.getLogger('sqlalchemy.engine')
sa_log.setLevel(logging.INFO)
message = self.trans_fixture.lazy('test ' + six.unichr(128))
sa_log.info(message)
expected = ('HAS CONTEXT [%s]: %s\n' % (ctxt.request_id,
six.text_type(message)))
self.assertEqual(expected, self.stream.getvalue())
def test_debugging_log(self):
message = 'baz'
self.log.debug(message)
self.assertEqual("NOCTXT: %s --DBG\n" % message,
self.stream.getvalue())
def test_message_logging(self):
# NOTE(luisg): Logging message objects with unicode objects
# may cause trouble by the logging mechanism trying to coerce
# the Message object, with a wrong encoding. This test case
# tests that problem does not occur.
ctxt = _fake_context()
ctxt.request_id = six.text_type('99')
message = self.trans_fixture.lazy('test ' + six.unichr(128))
self.log.info(message, context=ctxt)
expected = "HAS CONTEXT [%s]: %s\n" % (ctxt.request_id,
six.text_type(message))
self.assertEqual(expected, self.stream.getvalue())
def test_exception_logging(self):
# NOTE(dhellmann): If there is an exception and %(error_summary)s
# does not appear in the format string, ensure that it is
# appended to the end of the log lines.
ctxt = _fake_context()
ctxt.request_id = six.text_type('99')
message = self.trans_fixture.lazy('test ' + six.unichr(128))
try:
raise RuntimeError('test_exception_logging')
except RuntimeError:
self.log.warning(message, context=ctxt)
expected = 'RuntimeError: test_exception_logging\n'
self.assertTrue(self.stream.getvalue().endswith(expected))
def test_skip_logging_builtin_exceptions(self):
# NOTE(dhellmann): Several of the built-in exception types
# should not be automatically added to the log output.
ctxt = _fake_context()
ctxt.request_id = six.text_type('99')
message = self.trans_fixture.lazy('test ' + six.unichr(128))
ignored_exceptions = [
ValueError, TypeError, KeyError, AttributeError, ImportError
]
for ignore in ignored_exceptions:
try:
raise ignore('test_exception_logging')
except ignore as e:
self.log.warning(message, context=ctxt)
expected = '{}: {}'.format(e.__class__.__name__, e)
self.assertNotIn(expected, self.stream.getvalue())
def test_exception_logging_format_string(self):
# NOTE(dhellmann): If the format string includes
# %(error_summary)s then ensure the exception message ends up in
# that position in the output.
self.config(logging_context_format_string="A %(error_summary)s B")
ctxt = _fake_context()
ctxt.request_id = six.text_type('99')
message = self.trans_fixture.lazy('test ' + six.unichr(128))
try:
raise RuntimeError('test_exception_logging')
except RuntimeError:
self.log.warning(message, context=ctxt)
expected = 'A RuntimeError: test_exception_logging'
self.assertTrue(self.stream.getvalue().startswith(expected))
def test_no_exception_logging_format_string(self):
# NOTE(dhellmann): If there is no exception but the format
# string includes %(error_summary)s then ensure the "-" is
# inserted.
self.config(logging_context_format_string="%(error_summary)s")
ctxt = _fake_context()
ctxt.request_id = six.text_type('99')
message = self.trans_fixture.lazy('test ' + six.unichr(128))
self.log.info(message, context=ctxt)
expected = '-\n'
self.assertTrue(self.stream.getvalue().startswith(expected))
def test_unicode_conversion_in_adapter(self):
ctxt = _fake_context()
ctxt.request_id = six.text_type('99')
message = "Exception is (%s)"
ex = Exception(self.trans_fixture.lazy('test' + six.unichr(128)))
self.log.debug(message, ex, context=ctxt)
message = six.text_type(message) % ex
expected = "HAS CONTEXT [%s]: %s --DBG\n" % (ctxt.request_id,
message)
self.assertEqual(expected, self.stream.getvalue())
def test_unicode_conversion_in_formatter(self):
ctxt = _fake_context()
ctxt.request_id = six.text_type('99')
no_adapt_log = logging.getLogger('no_adapt')
no_adapt_log.setLevel(logging.INFO)
message = "Exception is (%s)"
ex = Exception(self.trans_fixture.lazy('test' + six.unichr(128)))
no_adapt_log.info(message, ex)
message = six.text_type(message) % ex
expected = "HAS CONTEXT [%s]: %s\n" % (ctxt.request_id,
message)
self.assertEqual(expected, self.stream.getvalue())
def test_user_identity_logging(self):
self.config(logging_context_format_string="HAS CONTEXT "
"[%(request_id)s "
"%(user_identity)s]: "
"%(message)s")
ctxt = _fake_context()
ctxt.request_id = u'99'
message = 'test'
self.log.info(message, context=ctxt)
expected = ("HAS CONTEXT [%s %s %s %s %s %s]: %s\n" %
(ctxt.request_id, ctxt.user, ctxt.tenant, ctxt.domain,
ctxt.user_domain, ctxt.project_domain,
six.text_type(message)))
self.assertEqual(expected, self.stream.getvalue())
def test_user_identity_logging_set_format(self):
self.config(logging_context_format_string="HAS CONTEXT "
"[%(request_id)s "
"%(user_identity)s]: "
"%(message)s",
logging_user_identity_format="%(user)s "
"%(tenant)s")
ctxt = _fake_context()
ctxt.request_id = u'99'
message = 'test'
self.log.info(message, context=ctxt)
expected = ("HAS CONTEXT [%s %s %s]: %s\n" %
(ctxt.request_id, ctxt.user, ctxt.tenant,
six.text_type(message)))
self.assertEqual(expected, self.stream.getvalue())
@mock.patch("datetime.datetime",
get_fake_datetime(
datetime.datetime(2015, 12, 16, 13, 54, 26, 517893)))
@mock.patch("dateutil.tz.tzlocal", new=mock.Mock(return_value=tz.tzutc()))
def test_rfc5424_isotime_format(self):
self.config(logging_default_format_string="%(isotime)s %(message)s")
message = "test"
expected = "2015-12-16T13:54:26.517893+00:00 %s\n" % message
self.log.info(message)
self.assertEqual(expected, self.stream.getvalue())
@mock.patch("datetime.datetime",
get_fake_datetime(
datetime.datetime(2015, 12, 16, 13, 54, 26)))
@mock.patch("time.time", new=mock.Mock(return_value=1450274066.000000))
@mock.patch("dateutil.tz.tzlocal", new=mock.Mock(return_value=tz.tzutc()))
def test_rfc5424_isotime_format_no_microseconds(self):
self.config(logging_default_format_string="%(isotime)s %(message)s")
message = "test"
expected = "2015-12-16T13:54:26.000000+00:00 %s\n" % message
self.log.info(message)
self.assertEqual(expected, self.stream.getvalue())
def test_can_process_strings(self):
expected = b'\xe2\x98\xa2'
if six.PY3:
# in PY3 logging format string should be unicode string
# or it will fail and inserting byte string in unicode string
# causes such formatting
expected = '\\xe2\\x98\\xa2'
self.log.info(b'%s', u'\u2622'.encode('utf8'))
self.assertIn(expected, self.stream.getvalue())
def test_dict_args_with_unicode(self):
msg = '%(thing)s'
arg = {'thing': '\xc6\x91\xc6\xa1\xc6\xa1'}
self.log.info(msg, arg)
self.assertIn(arg['thing'], self.stream.getvalue())
class ExceptionLoggingTestCase(LogTestBase):
"""Test that Exceptions are logged."""
def test_excepthook_logs_exception(self):
product_name = 'somename'
exc_log = log.getLogger(product_name)
self._add_handler_with_cleanup(exc_log)
excepthook = log._create_logging_excepthook(product_name)
try:
raise Exception('Some error happened')
except Exception:
excepthook(*sys.exc_info())
expected_string = ("CRITICAL somename [-] Unhandled error: "
"Exception: Some error happened")
self.assertIn(expected_string, self.stream.getvalue(),
message="Exception is not logged")
def test_excepthook_installed(self):
log.setup(self.CONF, "test_excepthook_installed")
self.assertTrue(sys.excepthook != sys.__excepthook__)
@mock.patch("datetime.datetime",
get_fake_datetime(
datetime.datetime(2015, 12, 16, 13, 54, 26, 517893)))
@mock.patch("dateutil.tz.tzlocal", new=mock.Mock(return_value=tz.tzutc()))
def test_rfc5424_isotime_format(self):
self.config(
logging_default_format_string="%(isotime)s %(message)s",
logging_exception_prefix="%(isotime)s ",
)
product_name = 'somename'
exc_log = log.getLogger(product_name)
self._add_handler_with_cleanup(exc_log)
excepthook = log._create_logging_excepthook(product_name)
message = 'Some error happened'
try:
raise Exception(message)
except Exception:
excepthook(*sys.exc_info())
expected_string = ("2015-12-16T13:54:26.517893+00:00 "
"Exception: %s" % message)
self.assertIn(expected_string,
self.stream.getvalue())
class FancyRecordTestCase(LogTestBase):
"""Test how we handle fancy record keys that are not in the
base python logging.
"""
def setUp(self):
super(FancyRecordTestCase, self).setUp()
# NOTE(sdague): use the different formatters to demonstrate format
# string with valid fancy keys and without. Slightly hacky, but given
# the way log objects layer up seemed to be most concise approach
self.config(logging_context_format_string="%(color)s "
"[%(request_id)s]: "
"%(instance)s"
"%(resource)s"
"%(message)s",
logging_default_format_string="%(missing)s: %(message)s")
self.colorlog = log.getLogger()
self._add_handler_with_cleanup(self.colorlog, handlers.ColorHandler)
self._set_log_level_with_cleanup(self.colorlog, logging.DEBUG)
def test_unsupported_key_in_log_msg(self):
# NOTE(sdague): exception logging bypasses the main stream
# and goes to stderr. Suggests on a better way to do this are
# welcomed.
error = sys.stderr
sys.stderr = six.StringIO()
self.colorlog.info("foo")
self.assertNotEqual(-1,
sys.stderr.getvalue().find("KeyError: 'missing'"))
sys.stderr = error
def _validate_keys(self, ctxt, keyed_log_string):
infocolor = handlers.ColorHandler.LEVEL_COLORS[logging.INFO]
warncolor = handlers.ColorHandler.LEVEL_COLORS[logging.WARN]
info_msg = 'info'
warn_msg = 'warn'
infoexpected = "%s %s %s" % (infocolor, keyed_log_string, info_msg)
warnexpected = "%s %s %s" % (warncolor, keyed_log_string, warn_msg)
self.colorlog.info(info_msg, context=ctxt)
self.assertIn(infoexpected, self.stream.getvalue())
self.assertEqual('\033[00;36m', infocolor)
self.colorlog.warn(warn_msg, context=ctxt)
self.assertIn(infoexpected, self.stream.getvalue())
self.assertIn(warnexpected, self.stream.getvalue())
self.assertEqual('\033[01;33m', warncolor)
def test_fancy_key_in_log_msg(self):
ctxt = _fake_context()
self._validate_keys(ctxt, '[%s]:' % ctxt.request_id)
def test_instance_key_in_log_msg(self):
ctxt = _fake_context()
ctxt.resource_uuid = '1234'
self._validate_keys(ctxt, ('[%s]: [instance: %s]' %
(ctxt.request_id, ctxt.resource_uuid)))
def test_resource_key_in_log_msg(self):
color = handlers.ColorHandler.LEVEL_COLORS[logging.INFO]
ctxt = _fake_context()
resource = 'resource-202260f9-1224-490d-afaf-6a744c13141f'
fake_resource = {'name': resource}
message = 'info'
self.colorlog.info(message, context=ctxt, resource=fake_resource)
expected = ('%s [%s]: [%s] %s\n' %
(color, ctxt.request_id, resource, message))
self.assertEqual(expected, self.stream.getvalue())
def test_resource_key_dict_in_log_msg(self):
color = handlers.ColorHandler.LEVEL_COLORS[logging.INFO]
ctxt = _fake_context()
type = 'fake_resource'
resource_id = '202260f9-1224-490d-afaf-6a744c13141f'
fake_resource = {'type': type,
'id': resource_id}
message = 'info'
self.colorlog.info(message, context=ctxt, resource=fake_resource)
expected = ('%s [%s]: [%s-%s] %s\n' %
(color, ctxt.request_id, type, resource_id, message))
self.assertEqual(expected, self.stream.getvalue())
class InstanceRecordTestCase(LogTestBase):
def setUp(self):
super(InstanceRecordTestCase, self).setUp()
self.config(logging_context_format_string="[%(request_id)s]: "
"%(instance)s"
"%(resource)s"
"%(message)s",
logging_default_format_string="%(instance)s"
"%(resource)s"
"%(message)s")
self.log = log.getLogger()
self._add_handler_with_cleanup(self.log)
self._set_log_level_with_cleanup(self.log, logging.DEBUG)
def test_instance_dict_in_context_log_msg(self):