1import logging
2import sys
3
4logger = logging.getLogger()
5logger.setLevel(logging.INFO)
6formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s',
7 '%m-%d-%Y %H:%M:%S')
8
9stdout_handler = logging.StreamHandler(sys.stdout)
10stdout_handler.setLevel(logging.DEBUG)
11stdout_handler.setFormatter(formatter)
12
13file_handler = logging.FileHandler('logs.log')
14file_handler.setLevel(logging.DEBUG)
15file_handler.setFormatter(formatter)
16
17logger.addHandler(file_handler)
18logger.addHandler(stdout_handler)
19
1import logging
2
3"""
4DEBUG
5INFO
6WARNING
7ERROR
8CRITICAL
9"""
10# asctime: time of the log was printed out
11# levelname: name of the log
12# datefmt: format the time of the log
13# give DEBUG log
14logging.basicConfig(format='%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
15 datefmt='%d-%m-%Y:%H:%M:%S',
16 level=logging.DEBUG,
17 filename='logs.txt')
18
19logger = logging.getLogger('my_app')
20
21logger.debug("This is a debug log")
22logger.info("This is an info log")
23logger.critical("This is critical")
24logger.error("An error occurred")
1import logging
2try:
3 from cStringIO import StringIO # Python 2
4except ImportError:
5 from io import StringIO
6
7class LevelFilter(logging.Filter):
8 def __init__(self, levels):
9 self.levels = levels
10
11 def filter(self, record):
12 return record.levelno in self.levels
13
14log_stream = StringIO()
15logging.basicConfig(stream=log_stream, level=logging.NOTSET)
16logging.getLogger().addFilter(LevelFilter((logging.INFO, logging.WARNING, logging.ERROR)))
17
18logging.info('hello world')
19logging.warning('be careful!')
20logging.debug("you won't see this")
21logging.error('you will see this')
22logging.critical('critical is no longer logged!')
23
24print(log_stream.getvalue())
25