Creating Logs Using Python Logger

Python

In this code snippet we set the logger to output log messages to a log file named 'train.log'. Each message will be time stamped and include the function name where the logging occurs. The lowest logging level is set to info so all debug messages will be ignored.

 1|  import logging
 2|  
 3|  logging.basicConfig(format='%(asctime)s[%(levelname)s] %(funcName)s: %(message)s',
 4|                          datefmt='%d/%m/%Y %I:%M:%S %p',
 5|                          filename='../logs/train.log',
 6|                          level=logging.INFO)
 7|  
 8|  # logger set to name of the script
 9|  LOG = logging.getLogger('__name__')
10|  
11|  LOG.info('Start')
12|  LOG.info('End')
13|  
14|  """List of log levels:
15|  LOG.debug() 
16|  LOG.info() 
17|  LOG.warning()
18|  LOG.error() 
19|  LOG.critical()
20|  LOG.exception()
21|  """
Did you find this snippet useful?

Sign up for free to to add this to your code library