Created
February 5, 2015 18:41
-
-
Save jathanism/a0d18171e5906fe475d6 to your computer and use it in GitHub Desktop.
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
| #!/usr/bin/env python | |
| # -*- coding: utf-8 -*- | |
| """ | |
| trigger_logging.py - Test log levels w/ Twisted logger. | |
| """ | |
| import os | |
| import logging | |
| import sys | |
| from twisted.python import log as txlog | |
| # Set the log settings | |
| LOG_LEVEL = logging.INFO | |
| if os.getenv('DEBUG'): | |
| LOG_LEVEL = logging.DEBUG | |
| if os.getenv('CRIT'): | |
| LOG_LEVEL = logging.CRITICAL | |
| LOG_FORMAT = "%(asctime)s [%(levelname)s]: %(message)s" | |
| LOG_FILE = '/dev/null' # This defaults to no logging obviously | |
| LOG_STREAM = None # This would be where you set sys.stdout | |
| class TriggerLogger(object): | |
| def __init__(self, log_level=LOG_LEVEL, log_format=LOG_FORMAT, | |
| log_file=LOG_FILE, stream=None): | |
| self.log_level = log_level | |
| self.log_format = log_format | |
| self.log_file = log_file | |
| self.stream = stream | |
| log_config = dict( | |
| level = self.log_level, | |
| format = log_format, | |
| ) | |
| if log_file is not None: | |
| log_config['filename'] = log_file | |
| if stream is not None: | |
| log_config.pop('filename', None) | |
| log_config['stream'] = stream | |
| # Configure Python logging | |
| logging.basicConfig(**log_config) | |
| # Start the Twisted logging observer | |
| self.observer = txlog.PythonLoggingObserver() | |
| self.observer.start() | |
| @classmethod | |
| def set_level(cls, log_level): | |
| cls.log_level = log_level | |
| @classmethod | |
| def msg(cls, *message, **kwargs): | |
| txlog.msg(*message, **kwargs) | |
| log = msg # For compat w/ logging.log() | |
| @classmethod | |
| def critical(cls, *message, **kwargs): | |
| txlog.msg(*message, logLevel=logging.CRITICAL, **kwargs) | |
| @classmethod | |
| def debug(cls, *message, **kwargs): | |
| txlog.msg(*message, logLevel=logging.DEBUG, **kwargs) | |
| @classmethod | |
| def error(cls, *message, **kwargs): | |
| txlog.msg(*message, logLevel=logging.ERROR, **kwargs) | |
| @classmethod | |
| def info(cls, *message, **kwargs): | |
| txlog.msg(*message, logLevel=logging.INFO, **kwargs) | |
| @classmethod | |
| def warning(cls, *message, **kwargs): | |
| txlog.msg(*message, logLevel=logging.WARNING, **kwargs) | |
| #log = TriggerLogger(log_file='/tmp/log') | |
| log = TriggerLogger(stream=sys.stdout) | |
| if __name__ == '__main__': | |
| log.info('This is informational.') | |
| log.critical('This is important!') | |
| log.debug('This is debug.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment