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
1# logging_example.py
2
3import logging
4
5# Create a custom logger
6logger = logging.getLogger(__name__)
7
8# Create handlers
9c_handler = logging.StreamHandler()
10f_handler = logging.FileHandler('file.log')
11c_handler.setLevel(logging.WARNING)
12f_handler.setLevel(logging.ERROR)
13
14# Create formatters and add it to handlers
15c_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
16f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
17c_handler.setFormatter(c_format)
18f_handler.setFormatter(f_format)
19
20# Add handlers to the logger
21logger.addHandler(c_handler)
22logger.addHandler(f_handler)
23
24logger.warning('This is a warning')
25logger.error('This is an error')
26
1import logging
2
3logger = logging.getLogger(__name__)
4
5FORMAT = '%(MYVAR)s %(asctime)s - %(levelname)s - %(message)s'
6logging.basicConfig(format=FORMAT, datefmt='%d/%m/%Y %H:%M:%S')
7
8logger.warning("'Twas brillig, and the slithy toves", extra={'MYVAR': 'Jabberwocky'})
9