what is logging in python code example
Example 1: python logging to file
import logging
import sys
logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s',
'%m-%d-%Y %H:%M:%S')
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setLevel(logging.DEBUG)
stdout_handler.setFormatter(formatter)
file_handler = logging.FileHandler('logs.log')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(stdout_handler)
Example 2: python logging to file
import logging
"""
DEBUG
INFO
WARNING
ERROR
CRITICAL
"""
logging.basicConfig(format='%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
datefmt='%d-%m-%Y:%H:%M:%S',
level=logging.DEBUG,
filename='logs.txt')
logger = logging.getLogger('my_app')
logger.debug("This is a debug log")
logger.info("This is an info log")
logger.critical("This is critical")
logger.error("An error occurred")
Example 3: create log in python
logging.basicConfig(filename="logfilename.log", level=logging.INFO)
logging.info('your text goes here')
logging.error('your text goes here')
logging.debug('your text goes here')
Example 4: logging.logger
import logging
logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.debug("some debugging...")
logger.error("some error...")
Example 5: logging request
Logging
In many cases it can be useful to print the
response and/or request details in order to
help you create the correct expectations and
send the correct requests. To do help you do thi
s you can use one of the predefined filters
supplied with REST Assured or you can use one of the shortcuts.
Request Logging
given().log().all(). .. //
Log all request specification details
including parameters, headers and body
given().log().params(). .. // Log only the parameters of the request
given().log().body(). .. // Log only the request body
given().log().headers(). .. // Log only the request headers
given().log().cookies(). .. // Log only the request cookies
given().log().method(). .. // Log only the request method
given().log().path(). .. // Log only the request path
Example 6: testing logging python
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'])