Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Configure log level and log-color via commandline #14

Merged
merged 1 commit into from
Mar 15, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions qatrfm/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

from qatrfm.environment import TerraformEnv
from qatrfm.utils import libutils
from qatrfm.utils.logger import QaTrfmLogger
from qatrfm.utils.logger import QaTrfmLogger, init_logging
from qatrfm.testcase import TrfmTestCase


Expand Down Expand Up @@ -76,9 +76,15 @@ def find_tf_file(basedir):
@click.option('--no-clean', 'no_clean', is_flag=True,
help="Don't clean the environment when the tests finish. "
"This is useful for debug and troubleshooting.")
def cli(test, path, tfvar, snapshots, no_clean):
@click.option('--loglevel', 'loglevel', type=click.Choice([
asmorodskyi marked this conversation as resolved.
Show resolved Hide resolved
'CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG']),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Owner

@jlausuch jlausuch Mar 14, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's not reinventing the wheel. These codes are passed to the python logger later, which is exactly the link you pasted. See this line
This just allows the user to select which log level to display.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought something like this pallets/click#605 , but looks like it is not supported yet ...

default='DEBUG', help="Specify default log level")
@click.option('--log-colors', 'logcolors', is_flag=True, help="Show different "
"loglevels in different colors", envvar='LOG_COLORS')
def cli(test, path, tfvar, snapshots, no_clean, loglevel, logcolors):
""" Create a terraform environment and run the test(s)"""

init_logging(loglevel, logcolors)
logger = QaTrfmLogger.getQatrfmLogger(__name__)
test_array = test.split(',')

Expand Down
73 changes: 41 additions & 32 deletions qatrfm/utils/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,57 +11,66 @@
""" QaTrfm custom Logger Class

It defines a specific format of the log messages.
If LOG_COLORS=1 is exported, it will print the messages in different colors
according to it's level.
"""

import logging
import os


class QaTrfmLogger(logging.Logger):

def __init__(self, logger_name, level="DEBUG"):
colors = False

def __init__(self, logger_name):
"""Initialize QaTrfmLogger Class"""
self.colors = False
if ('LOG_COLORS' in os.environ):
self.colors = True
format = "\033[37;48mqatrfm.%(levelname)s: \033[0m%(message)s"
else:
self.colors = False
format = "qatrfm.%(levelname)s: %(message)s"
logging.basicConfig(level=logging.DEBUG, format=format)
return super(QaTrfmLogger, self).__init__(logger_name, level)
return super().__init__(logger_name)

@staticmethod
def colorize(msg, color):
COLORS_MAP = {
'blue': 34, 'green': 32, 'red': 31, 'yellow': 33,
'lightgrey': 37
}
if color in COLORS_MAP.keys():
return "\033[1;{}m{}\033[0m".format(COLORS_MAP[color], msg)
return msg

def info(self, msg, *args, **kwargs):
if (self.colors):
msg = ("\033[1;34m {}\033[0m".format(msg))
else:
msg = (" {}".format(msg))
super(QaTrfmLogger, self).info(msg, *args, **kwargs)
if (QaTrfmLogger.colors):
msg = QaTrfmLogger.colorize(msg, 'blue')
super().info(msg, *args, **kwargs)

def success(self, msg, *args, **kwargs):
if (self.colors):
msg = ("\033[1;32m {}\033[0m".format(msg))
else:
msg = (" {}".format(msg))
super(QaTrfmLogger, self).info(msg, *args, **kwargs)
if (QaTrfmLogger.colors):
msg = QaTrfmLogger.colorize(msg, 'green')
super().info(msg, *args, **kwargs)

def error(self, msg, *args, **kwargs):
if (self.colors):
msg = ("\033[1;31m{}\033[0m".format(msg))
super(QaTrfmLogger, self).error(msg, *args, **kwargs)
if (QaTrfmLogger.colors):
msg = QaTrfmLogger.colorize(msg, 'red')
super().error(msg, *args, **kwargs)

def critical(self, msg, *args, **kwargs):
if (QaTrfmLogger.colors):
msg = QaTrfmLogger.colorize(msg, 'red')
super().critical(msg, *args, **kwargs)

def warning(self, msg, *args, **kwargs):
if (self.colors):
msg = ("\033[1;33m{}\033[0m".format(msg))
super(QaTrfmLogger, self).warning(msg, *args, **kwargs)
if (QaTrfmLogger.colors):
msg = QaTrfmLogger.colorize(msg, 'yellow')
super().warning(msg, *args, **kwargs)

@staticmethod
def getQatrfmLogger(name):
logging.setLoggerClass(QaTrfmLogger)
return logging.getLogger(name)


logging.setLoggerClass(QaTrfmLogger)
logging.getLogger("paramiko.transport").setLevel(logging.WARNING)
logging.getLogger("paramiko.transport.sftp").setLevel(logging.WARNING)
def init_logging(level, colors):
fmt = "%(levelname)-8s %(name)-12s: %(message)s"
if colors:
fmt = QaTrfmLogger.colorize(fmt[:-11], 'lightgrey')
fmt += '%(message)s'
logging.basicConfig(level=level, format=fmt)
logging.getLogger("paramiko.transport").setLevel(logging.WARNING)
logging.getLogger("paramiko.transport.sftp").setLevel(logging.WARNING)
QaTrfmLogger.colors = colors