1import logging
2logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
3logging.debug('This is debug message')
4logging.info('This is information message')
5logging.warning('This is warning message')
6logging.error('This is warning message')
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
2
3logging.basicConfig(
4 level=logging.INFO,
5 format="%(asctime)s [%(levelname)s] %(message)s",
6 handlers=[
7 logging.FileHandler("debug.log"),
8 logging.StreamHandler()
9 ]
10)
1logging.basicConfig(filename="logfilename.log", level=logging.INFO)
2# Log Creation
3
4logging.info('your text goes here')
5logging.error('your text goes here')
6logging.debug('your text goes here')
7
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