python application logging code example
Example 1: python log to file and console
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler("debug.log"),
logging.StreamHandler()
]
)
Example 2: python logging to console exqmple
import sys
# ...
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
Example 3: testing logging python
# can be done by using unittest's assertLogs
from unittest import TestCase
class MyTest(TestCase):
def test_logs(self):
with self.assertLogs('foo', level='INFO') as cm:
logging.getLogger('foo').info('first message')
logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
'ERROR:foo.bar:second message'])