Show pageOld revisionsBacklinksBack to top This page is read only. You can view the source, but not change it. Ask your administrator if you think this is wrong. ====== Logging ====== **General Information** Using the logging module to output to a log file and the console. ---- ====== Usage ====== Run the logging_example.py script to see output to the console and a log file. <code bash> ./logging_example.py </code> \\ Displayed on the console<code bash>CRITICAL Urgent message! Display in log AND console.</code> \\ Written to log file<code bash>[2018-07-08 23:05:53,148] INFO [__main__:50] Testing info level message. [2018-07-08 23:05:53,149] CRITICAL [__main__:51] Urgent message! Display in log AND console.</code> ---- ====== The Code ====== <code python logging_example.py> #!/usr/bin/python ####---- Logging Configuration ----#### LOGGING_CONFIG = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", }, 'simple': { 'format': '%(levelname)s %(message)s', }, }, 'handlers': { 'logfile': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': '/var/log/test.log', 'maxBytes': 500000000, # 500 MB 'backupCount': 10, 'formatter': 'verbose', }, 'console': { 'level': 'CRITICAL', 'class': 'logging.StreamHandler', 'formatter': 'simple', }, }, 'loggers': { '__main__': { 'handlers': ['logfile', 'console'], 'level': 'DEBUG', 'propagate': True, }, }, } ####---- End of Logging Config ----#### # Logging Module with config capabilities import logging.config # Create logging instance logger = logging.getLogger(__name__) # Load logging configuration logging.config.dictConfig(LOGGING_CONFIG) # Send log messages logger.info("Testing info level message.") logger.critical("Urgent message! Display in log AND console.") </code> ---- python_wiki/logging.txt Last modified: 2019/05/25 23:50(external edit)