Created
August 22, 2016 19:57
-
-
Save kkirsche/fd6a520dcb66e2aba064ae8b17a3240c to your computer and use it in GitHub Desktop.
Python based stdout logger and logger using logging.handlers.SysLogHandler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import logging | |
| from logging.handlers import SysLogHandler | |
| import sys | |
| def create_logger(name, verbosity): | |
| """create_logger uses a name and verbosity level. The name is most commonly | |
| the __name__ variable and verbosity is most often passed to the program | |
| from command line arguments via ConfigParser/configparser. This then sets | |
| the log level to Warning (no verbosity), Information (verbosity 1), or | |
| Debug (verbosity 2). If the verbosity is greater than 2, it is reduced to | |
| the maximum log level permitted by the application, where maximum is the | |
| most verbose logging option. create_logger then returns a tuple of the log | |
| instance and the log level which was set. The log level value is defined by | |
| the python logging package. | |
| """ | |
| log_level = { | |
| 0: logging.WARNING, | |
| 1: logging.INFO, | |
| 2: logging.DEBUG, | |
| }.get(verbosity, logging.WARNING) | |
| log = logging.getLogger(name) | |
| log.setLevel(log_level) | |
| stdout_handler = logging.StreamHandler() | |
| log.addHandler(stdout_handler) | |
| if sys.platform == "darwin": | |
| # Apple made 10.5+ more secure by disabling network syslog: | |
| address = "/var/run/syslog" | |
| elif sys.platform == 'linux2': | |
| address = '/dev/log' | |
| else: | |
| address = ('localhost', 514) | |
| facility = SysLogHandler.LOG_DAEMON | |
| syslog_handler = SysLogHandler(address=address, facility=facility) | |
| log.addHandler(syslog_handler) | |
| if log_level == logging.INFO: | |
| log.info("Verbosity level set to INFO") | |
| elif log_level == logging.DEBUG: | |
| log.debug("Verbosity level set to DEBUG") | |
| return (log, log_level) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment