我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用colorlog.ColoredFormatter()。
def create_logger(): """ Setup the logging environment """ log = logging.getLogger() # root logger log.setLevel(logging.INFO) format_str = '%(asctime)s - %(levelname)-8s - %(message)s' date_format = '%Y-%m-%d %H:%M:%S' if HAVE_COLORLOG and os.isatty(2): cformat = '%(log_color)s' + format_str colors = {'DEBUG': 'reset', 'INFO': 'reset', 'WARNING': 'bold_yellow', 'ERROR': 'bold_red', 'CRITICAL': 'bold_red'} formatter = colorlog.ColoredFormatter(cformat, date_format, log_colors=colors) else: formatter = logging.Formatter(format_str, date_format) stream_handler = logging.StreamHandler() stream_handler.setFormatter(formatter) log.addHandler(stream_handler) return logging.getLogger(__name__)
def setup_logging(log_level=logging.INFO): """Set up the logging.""" logging.basicConfig(level=log_level) fmt = ("%(asctime)s %(levelname)s (%(threadName)s) " "[%(name)s] %(message)s") colorfmt = "%(log_color)s{}%(reset)s".format(fmt) datefmt = '%Y-%m-%d %H:%M:%S' # Suppress overly verbose logs from libraries that aren't helpful logging.getLogger('requests').setLevel(logging.WARNING) logging.getLogger('urllib3').setLevel(logging.WARNING) logging.getLogger('aiohttp.access').setLevel(logging.WARNING) try: from colorlog import ColoredFormatter logging.getLogger().handlers[0].setFormatter(ColoredFormatter( colorfmt, datefmt=datefmt, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red', } )) except ImportError: pass logger = logging.getLogger('') logger.setLevel(log_level)
def get(cls, tag): """ Get the global logger instance for the given tag :param tag: the log tag :return: the logger instance """ if tag not in cls._LOGGERS: if cls._use_color: handler = colorlog.StreamHandler() handler.setFormatter(colorlog.ColoredFormatter( \ ' %(log_color)s%(name)s/%(levelname)-8s%(reset)s |' ' %(log_color)s%(message)s%(reset)s')) else: handler = logging.StreamHandler() handler.setFormatter(logging.Formatter( \ ' %(name)s/%(levelname)-8s | %(message)s')) logger = logging.getLogger(tag) logger.addHandler(handler) cls._LOGGERS[tag] = logger return cls._LOGGERS[tag]
def setup_logger(name, level, colors=COLORS, format_string="%(purple)s%(name)s> %(log_color)s%(message)s"): """Set up a particular logger with overridden behavior. Args: name (str): The name of the logger. level (int): The log level to set this logger to. colors (dict): A dictionary of log colors. format_string (str): The format of the log message. """ logger_ = logging.getLogger(name) logger_.setLevel(level) formatter = ColoredFormatter(format_string, reset=True, log_colors=colors) if logger_.handlers: logger_.handlers.pop() handler = logging.StreamHandler() handler.setFormatter(formatter) logger_.addHandler(handler) logger_.propagate = False return logger_ # Make the logger and output_logger available for import from elsewhere.
def init_logger(self): self._mylogger = colorlog.getLogger("sequanix") """self._fh = open(self._logger_output, "w") self._handler = colorlog.StreamHandler(self._fh) formatter = colorlog.ColoredFormatter( "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red', } ) self._handler.setFormatter(formatter) self._mylogger.addHandler(self._handler) """
def __init__(self): if _colorlog: self.handler = colorlog.StreamHandler() self.handler.setFormatter(colorlog.ColoredFormatter( '%(log_color)s%(message)s', datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', }, style='%' )) else: # Default to basic logging self.handler = logging.StreamHandler() self.logger = logging.getLogger('cli') self.logger.addHandler(self.handler) self.logger.setLevel(logging.DEBUG) self.logger.propagate = False
def create_console_handler(verbose_level): clog = logging.StreamHandler() formatter = ColoredFormatter( "%(log_color)s[%(asctime)s %(levelname)-8s%(module)s]%(reset)s " "%(white)s%(message)s", datefmt="%H:%M:%S", reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red', }) clog.setFormatter(formatter) if verbose_level == 0: clog.setLevel(logging.WARN) elif verbose_level == 1: clog.setLevel(logging.INFO) else: clog.setLevel(logging.DEBUG) return clog
def create_default_logger(level=logging.DEBUG, fname='/tmp/ethereumd-proxy.log'): handler = logging.FileHandler(fname) formatter = colorlog.ColoredFormatter( "%(log_color)s[%(asctime)s %(levelname)s " "%(name)s - %(module)s:%(funcName)s:%(lineno)d]" "%(reset)s %(blue)s%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', }, secondary_log_colors={}, style='%' ) handler.setFormatter(formatter) handler.setLevel(level) logger = colorlog.getLogger() logger.addHandler(handler) logger.setLevel(level) return logger
def setup_logging(): # pragma: no cover root_logger = logging.getLogger() root_logger.setLevel(logging.DEBUG) handler = logging.StreamHandler() formatter = ColoredFormatter( "%(cyan)s%(name)s > %(log_color)s%(message)s", reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'blue', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', 'SUCCESS': 'green' } ) handler.setFormatter(formatter) root_logger.addHandler(handler) # Silence noisy loggers logging.getLogger('sh').setLevel(logging.WARNING)
def __init__(self, name='', fname='', level='INFO'): if fname: try: self.fout = open(fname, 'w') except IOError: print('[ERROR] Failed to open %s for writing'%fname) self.fout = None else: self.fout = None self.logger = logging.getLogger(name) self.handler = colorlog.StreamHandler() self.handler.setFormatter(colorlog.ColoredFormatter( '%(log_color)s%(asctime)s %(levelname)s:%(name)s:%(message)s%(reset)s', log_colors={ 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red' })) self.logger.addHandler(self.handler) self.setLevel(level)
def setup_logger(): from colorlog import ColoredFormatter from gettext import gettext as _ # noqa try: """Return a logging obj with a default ColoredFormatter.""" formatter = ColoredFormatter( "%(asctime)s %(name)-12s (%(threadName)-9s) %(log_color)s%(levelname)-8s%(reset)s (%(funcName)-5s) %(message_log_color)s%(message)s", # noqa datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'bold_red', 'TRACE': 'purple' }, secondary_log_colors={ 'message': { 'ERROR': 'red', 'CRITICAL': 'red', 'DEBUG': 'yellow', 'INFO': 'yellow,bg_blue' } }, style='%' ) handler = logging.StreamHandler() handler.setFormatter(formatter) logging.getLogger('').addHandler(handler) logging.root.setLevel(logging.DEBUG) except ImportError: # No color available, use default config logging.basicConfig(format='%(levelname)s: %(message)s') logging.warn("Disabling color, you really want to install colorlog.")
def main(): # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.INFO) # create formatter formatter = ColoredFormatter('%(log_color)s%(levelname)s%(reset)s:%(bold_white)s%(name)s%(reset)s - ' '%(cyan)s%(message)s%(reset)s') # add formatter to ch ch.setFormatter(formatter) # add ch to logger logger = logging.getLogger('packet_stream') logger.setLevel(logging.INFO) logger.addHandler(ch) keypair = load_ssb_secret()['keypair'] loop = get_event_loop() packet_stream = PSClient('127.0.0.1', 8008, keypair, bytes(keypair.verify_key), loop=loop) loop.run_until_complete(_main(packet_stream)) loop.close()
def format(self, record): if not hasattr(record, self.log_color_field): setattr(record, self.log_color_field, '?') record.__dict__.update(escape_codes) color_field = self._get_color_field(record) if color_field and color_field in self.log_colors: color = self.log_colors[color_field] record.log_color = escape_codes[color] else: record.log_color = "" # Format the message if sys.version_info > (2, 7): message = super(ColoredFormatter, self).format(record) else: message = logging.Formatter.format(self, record) # Add a reset code to the end of the message # (if it wasn't explicitly added in format str) if self.reset and not message.endswith(escape_codes['reset']): message += escape_codes['reset'] return message
def configure_logging(): root_logger = logging.getLogger() console = logging.StreamHandler() console.setLevel(logging.DEBUG) # Create a colorized formatter formatter = ColoredFormatter( "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s", datefmt=None, reset=True, log_colors={ "DEBUG": "cyan", "INFO": "green", "WARNING": "yellow", "ERROR": "red", "CRITICAL": "red,bg_white", }, secondary_log_colors={}, style="%" ) # Add the formatter to the console handler, and the console # handler to the root logger. console.setFormatter(formatter) root_logger.addHandler(console)
def get_logger(): logger = logging.getLogger('abci.app') if logger.hasHandlers(): return logger formatter = colorlog.ColoredFormatter( "%(log_color)s%(levelname)-8s%(reset)s %(white)s%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', }, secondary_log_colors={}, style='%') handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.INFO) return logger
def create_logger(app): logger = logging.getLogger('pytendermint.app') handler = logging.StreamHandler() logger.setLevel(logging.INFO) if app.debug: logger.setLevel(logging.DEBUG) formatter = colorlog.ColoredFormatter( "%(log_color)s%(levelname)-8s%(reset)s %(white)s%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', }, secondary_log_colors={}, style='%') handler.setFormatter(formatter) logger.addHandler(handler) return logger
def __init__(self, name = ''): conf = com_config.Config() self.config = conf.getconfig() self.logger = logging.Logger(name, logging.DEBUG) self.logger.name = name # Formatter formatterfile = logging.Formatter('%(asctime)s %(levelname)s : %(name)s - %(message)s', datefmt='%d/%m/%Y %H:%M:%S') formatterconsole = colorlog.ColoredFormatter('%(asctime)s %(log_color)s%(levelname)s : %(name)s - %(message)s', datefmt='%d/%m/%Y %H:%M:%S', log_colors={'DEBUG': 'white', 'INFO': 'green', 'WARNING': 'bold_yellow', 'ERROR': 'bold_red', 'CRITICAL': 'bold_red'}) # First logger (file) self.logger.setLevel(logging.DEBUG) file_handler = RotatingFileHandler(self.config['LOGGER']['logfile'], 'a', int(self.config['LOGGER']['logfilesize']), 1) file_handler.setLevel(int(self.config['LOGGER']['levelfile'])) file_handler.setFormatter(formatterfile) self.logger.addHandler(file_handler) # second logger (console) steam_handler = logging.StreamHandler() steam_handler.setLevel(int(self.config['LOGGER']['levelconsole'])) steam_handler.setFormatter(formatterconsole) self.logger.addHandler(steam_handler)
def setup_logger(): """Setup a colored logger if available and possible""" logger = logging.getLogger('clikraken') logger.setLevel(logging.DEBUG) # log to stdout from DEBUG to INFO ch_out = logging.StreamHandler(sys.stdout) ch_out.setLevel(logging.DEBUG) ch_out.addFilter(LessThanFilter(logging.WARNING)) # WARNING and above goes to stderr ch_err = logging.StreamHandler(sys.stderr) ch_err.setLevel(logging.WARNING) format_str = '{levelname:8} - {message}' # basic formatter f = logging.Formatter(fmt=format_str, style='{') # colored formatted if have_colorlog: cf = colorlog.ColoredFormatter(fmt='{log_color}' + format_str, style='{') else: cf = f # only use the colored formatter when we are outputting to a terminal if os.isatty(2): ch_out.setFormatter(cf) ch_err.setFormatter(cf) else: ch_out.setFormatter(f) ch_err.setFormatter(f) logger.addHandler(ch_out) logger.addHandler(ch_err) return logger
def set_format(frmt, frmt_col=None, datefmt=None): if frmt_col: try: formatter = ColoredFormatter(frmt_col, datefmt=datefmt) return formatter except: pass formatter = logging.Formatter(frmt) return formatter
def init_logger(logger): """Initialize a logger object.""" colored_handler = colorlog.StreamHandler() colored_handler.setFormatter(colorlog.ColoredFormatter( \ "%(green)s%(asctime)s%(reset)s " + \ "%(blue)s[%(cyan)s%(name)s%(blue)s]%(reset)s " + \ "%(bold)s%(levelname)s%(reset)s " + \ "%(message)s")) logger.setLevel(logging.INFO) logger.addHandler(colored_handler)
def setup_logging(extra_handlers=(), config_file='chainsaw.log'): logger = logging.getLogger('tripleohelper') logger.setLevel(logging.DEBUG) formatter = logging.Formatter( "%(asctime)s::%(levelname)s::%(message)s") stream_handler = logging.StreamHandler(stream=sys.stdout) stream_handler.setFormatter(formatter) file_handler = logging.FileHandler(config_file, mode='w') file_handler.setFormatter(formatter) try: import colorlog colored_formatter = colorlog.ColoredFormatter( "%(log_color)s%(asctime)s::%(levelname)s::%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red' } ) stream_handler.setFormatter(colored_formatter) except ImportError: pass logger.addHandler(stream_handler) logger.addHandler(file_handler) for handler in extra_handlers: logger.addHandler(handler)
def set_logger(cls, level=logging.DEBUG): """ Configure logging :param level: expected level of verbosity This utility function should probably be put elsewhere """ handler = colorlog.StreamHandler() formatter = colorlog.ColoredFormatter( "%(asctime)-2s %(log_color)s%(message)s", datefmt='%H:%M:%S', reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', }, secondary_log_colors={}, style='%' ) handler.setFormatter(formatter) logging.getLogger('').handlers = [] logging.getLogger('').addHandler(handler) logging.getLogger('').setLevel(level=level)
def setup_logging(): """ Setup initial logging configuration """ from ...config import __tool_name__, DEBUG_LEVEL # Init logger logger = logging.getLogger() # Set log level logger.setLevel(abs(50 - (DEBUG_LEVEL if DEBUG_LEVEL < 5 else 5) * 10)) # Set file log format file_format = logging.Formatter('[%(levelname)s] %(asctime)s - %(message)s', "%Y-%m-%d %H:%M:%S") log_file = logging.FileHandler(filename="%s.log" % __tool_name__) log_file.setFormatter(file_format) # Handler: console formatter = ColoredFormatter( "[ %(log_color)s*%(reset)s ] %(blue)s%(message)s", # "[ %(log_color)s%(levelname)-8s%(reset)s] %(blue)s%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', }, secondary_log_colors={}, style='%' ) log_console = logging.StreamHandler() log_console.setFormatter(formatter) # -------------------------------------------------------------------------- # Add all of handlers to logger config # -------------------------------------------------------------------------- logger.addHandler(log_console) logger.addHandler(log_file)
def setup_loggers(config): loglevel = getattr( logging, config["LogLevel"]) if 'LogLevel' in config else logging.WARN logger = logging.getLogger() logger.setLevel(loglevel) if 'LogFile' in config and config['LogFile'] != '__screen__': logfile = config['LogFile'] if not os.path.isdir(os.path.dirname(logfile)): warnings.warn("Logging directory {0} does not exist".format( os.path.abspath(os.path.dirname(logfile)))) sys.exit(-1) flog = logging.FileHandler(logfile) flog.setFormatter(logging.Formatter( '[%(asctime)s, %(levelno)d, %(module)s] %(message)s', "%H:%M:%S")) logger.addHandler(flog) else: clog = logging.StreamHandler() formatter = ColoredFormatter( "%(log_color)s[%(asctime)s %(levelname)-8s%(module)s]%(reset)s " "%(white)s%(message)s", datefmt="%H:%M:%S", reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red', }) clog.setFormatter(formatter) clog.setLevel(loglevel) logger.addHandler(clog)
def get_default_formatter(): """ Returns the default formatter used to log messages for LXDock. """ return ColoredFormatter('%(log_color)s%(message)s', log_colors=LOG_COLORS)
def get_per_container_formatter(container_name): """ Returns a logging formatter which prefixes each message with a container name. """ return ColoredFormatter( '%(log_color)s==> {name}: %(message)s'.format(name=container_name), log_colors=LOG_COLORS)
def init_logging(logger, verbosity): if verbosity > 0: console = logging.StreamHandler() try: # noinspection PyUnresolvedReferences from colorlog import ColoredFormatter formatter = ColoredFormatter('{yellow}{asctime}{reset} ' '[{log_color}{levelname}{reset}] ' '{white}{message}{reset}', style='{') except ImportError: formatter = logging.Formatter('{asctime} [{levelname}] {message}', style='{') console.setFormatter(formatter) console.setLevel(logging.DEBUG) logger.addHandler(console) # Stop PIL from excessive logging pil_logger = logging.getLogger('PIL') pil_logger.setLevel(logging.INFO) django_db_logger = logging.getLogger('django.db') django_db_logger.setLevel(logging.INFO) if verbosity >= 2: logger.setLevel(logging.INFO) if verbosity >= 3: logger.setLevel(logging.DEBUG)
def attach_to_log(log_level = logging.DEBUG, blacklist = ['TerminalIPythonApp','PYREADLINE']): ''' Attach a stream handler to all loggers. ''' try: from colorlog import ColoredFormatter formatter = ColoredFormatter( ("%(log_color)s%(levelname)-8s%(reset)s " + "%(filename)17s:%(lineno)-4s %(blue)4s%(message)s"), datefmt = None, reset = True, log_colors = {'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red' } ) except ImportError: formatter = logging.Formatter( "[%(asctime)s] %(levelname)-7s (%(filename)s:%(lineno)3s) %(message)s", "%Y-%m-%d %H:%M:%S") handler_stream = logging.StreamHandler() handler_stream.setFormatter(formatter) handler_stream.setLevel(log_level) for logger in logging.Logger.manager.loggerDict.values(): if (logger.__class__.__name__ != 'Logger' or logger.name in blacklist): continue logger.addHandler(handler_stream) logger.setLevel(log_level) np.set_printoptions(precision=5, suppress=True)
def create_logger() -> logging.Logger: root = logging.getLogger('pr0n_crawler') root.setLevel(logging.INFO) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.INFO) ch.setFormatter(ColoredFormatter( '[%(log_color)s%(levelname)s%(reset)s] %(bold)s%(site_name)s%(reset)s' ' (%(videos_current_number)s): %(message)s' )) root.addHandler(ch) return root
def setup_logging(level=logging.DEBUG): root_logger = logging.getLogger() for handler in root_logger.handlers: if isinstance(handler, logging.StreamHandler): return if level > logging.DEBUG: date_format = '%Y-%m-%d %H:%M:%S' else: date_format = None formatter = ColoredFormatter( "%(log_color)s%(asctime)s - %(name)s - %(message)s", datefmt=date_format, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red' } ) stream_out = logging.StreamHandler() stream_out.setLevel(level) stream_out.setFormatter(formatter) root_logger.addHandler(stream_out) logging.getLogger('boto3').setLevel(logging.CRITICAL) logging.getLogger('botocore').setLevel(logging.CRITICAL) logging.getLogger('paramiko').setLevel(logging.CRITICAL) logging.getLogger('requests').setLevel(logging.CRITICAL) logging.getLogger('tldextract').setLevel(logging.CRITICAL) logging.getLogger('spacel').setLevel(logging.DEBUG)
def setup_logger(config): try: log_level = int(config['DEFAULT']['logLevel']) except ValueError: log_level = config['DEFAULT']['logLevel'] _LOGGER.setLevel(log_level) ch = logging.StreamHandler() ch.setLevel(log_level) try: from colorlog import ColoredFormatter formatter = ColoredFormatter( "%(log_color)s%(levelname)-8s %(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red', } ) except ImportError: formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) _LOGGER.addHandler(ch)
def main(): logging.getLogger().setLevel(logging.INFO) if sys.stderr.isatty(): try: import colorlog except ImportError: pass else: formatter = colorlog.ColoredFormatter( '%(log_color)s%(levelname)s:%(name)s:%(reset)s %(message)s') handler = logging.StreamHandler() handler.setFormatter(formatter) logging.getLogger().addHandler(handler) # This is a no-op if we already attached a (coloured log) handler logging.basicConfig() parser.parse_args(namespace=args) if 'VECTIS_DEBUG_COMMAND_LINE' in os.environ: args.dump() return try: importlib.import_module( 'vectis.commands.' + args._subcommand.replace('-', '_')).run(args) except KeyboardInterrupt: raise SystemExit(130) except subprocess.CalledProcessError as e: logger.error('%s', e) raise SystemExit(1) except Error as e: logger.error('%s', e) raise SystemExit(1)
def test_example(): """Tests the usage example from the README""" import colorlog handler = colorlog.StreamHandler() handler.setFormatter(colorlog.ColoredFormatter( '%(log_color)s%(levelname)s:%(name)s:%(message)s')) logger = colorlog.getLogger('example') logger.addHandler(handler)
def create_and_test_logger(test_logger): def function(*args, **kwargs): validator = kwargs.pop('validator', None) formatter = colorlog.ColoredFormatter(*args, **kwargs) stream = logging.StreamHandler() stream.setLevel(logging.DEBUG) stream.setFormatter(formatter) logger = logging.getLogger(inspect.stack()[1][3]) logger.setLevel(logging.DEBUG) logger.addHandler(stream) return test_logger(logger, validator) return function
def create_console_handler(verbose_level): """ Set up the console logging for a transaction processor. Args: verbose_level (int): The log level that the console should print out """ clog = logging.StreamHandler() formatter = ColoredFormatter( "%(log_color)s[%(asctime)s.%(msecs)03d " "%(levelname)-8s %(module)s]%(reset)s " "%(white)s%(message)s", datefmt="%Y-%m-%d %H:%M:%S", reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red', }) clog.setFormatter(formatter) if verbose_level == 0: clog.setLevel(logging.WARN) elif verbose_level == 1: clog.setLevel(logging.INFO) else: clog.setLevel(logging.DEBUG) return clog
def setup_loggers(config): if 'log_level' in config: log_level = getattr(logging, config["log_level"]) else: log_level = logging.WARN LOGGER.setLevel(log_level) clog = logging.StreamHandler() formatter = ColoredFormatter( '%(log_color)s[%(asctime)s %(module)s]%(reset)s ' '%(white)s%(message)s', datefmt="%H:%M:%S", reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red', 'SECRET': 'black' }) clog.setFormatter(formatter) clog.setLevel(log_level) LOGGER.addHandler(clog) if 'log_file' in config: flog = logging.FileHandler(config['log_file']) LOGGER.addHandler(flog) else: flog = logging.FileHandler('ias_proxy.log') LOGGER.addHandler(flog) LOGGER.warning('Log file not specified. Guess you found it though.') LOGGER.info("Logger Initialized!") LOGGER.info("Config: %s", config)
def create_console_handler(verbose_level): clog = logging.StreamHandler() formatter = ColoredFormatter( "%(log_color)s[%(asctime)s.%(msecs)03d " "%(levelname)-8s %(module)s]%(reset)s " "%(white)s%(message)s", datefmt="%Y-%m-%d %H:%M:%S", reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red', }) clog.setFormatter(formatter) if verbose_level == 0: clog.setLevel(logging.WARN) elif verbose_level == 1: clog.setLevel(logging.INFO) else: clog.setLevel(logging.DEBUG) return clog