Skip to content

Commit

Permalink
Add CustomFormatter class colouring logging output
Browse files Browse the repository at this point in the history
Change pre-logger criticals to format strings and add colouring
  • Loading branch information
LegenJCdary committed Apr 19, 2022
1 parent a2c68e1 commit 4799820
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 12 deletions.
8 changes: 4 additions & 4 deletions source/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import argparse
import datetime
import errno
from ansible_deployer.modules.globalvars import SUBCOMMANDS
from ansible_deployer.modules.globalvars import SUBCOMMANDS, PRINT_FAIL, PRINT_END
from ansible_deployer.modules.configs.config import Config
from ansible_deployer.modules.locking.locking import Locking
from ansible_deployer.modules.outputs.logging import Loggers
Expand Down Expand Up @@ -46,8 +46,8 @@ def parse_options(argv):

if not arguments.subcommand:
sub_string = ", ".join(SUBCOMMANDS).strip(", ")
print(f"[CRITICAL]: First positional argument (subcommand) is required! Available commands"
f" are: {sub_string}.")
print(f"{PRINT_FAIL}[CRITICAL]: First positional argument (subcommand) is required!"
f" Available commands are: {sub_string}.{PRINT_END}")
sys.exit(57)

options = {}
Expand Down Expand Up @@ -77,7 +77,7 @@ def main():
start_ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")

if len(sys.argv) < 2:
print("[CRITICAL]: Too few arguments", file=sys.stderr)
print(f"{PRINT_FAIL}[CRITICAL]: Too few arguments{PRINT_END}", file=sys.stderr)
sys.exit(2)
options = parse_options(sys.argv[1:])

Expand Down
2 changes: 2 additions & 0 deletions source/modules/globalvars.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@
APP_CONF = "/etc/ansible-deployer"
CFG_PERMISSIONS = "0o644"
SUBCOMMANDS = ("run", "list", "lock", "unlock", "verify", "show")
PRINT_FAIL = '\033[91m'
PRINT_END = '\033[0m'
31 changes: 29 additions & 2 deletions source/modules/outputs/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def set_logging(options: dict):
logger = logging.getLogger("ansible-deployer_log")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s [%(levelname)s]: %(message)s")
console_formatter = logging.Formatter("\n%(asctime)s [%(levelname)s]: %(message)s\n")
console_formatter = "\n%(asctime)s [%(levelname)s]: %(message)s\n"

if options["syslog"]:
rsys_handler = log_han.SysLogHandler(address="/dev/log")
Expand All @@ -26,7 +26,8 @@ def set_logging(options: dict):
logger.addHandler(rsys_handler)

console_handler = logging.StreamHandler()
console_handler.setFormatter(console_formatter)
console_formatter = "\n%(asctime)s [%(levelname)s]: %(message)s\n"
console_handler.setFormatter(CustomFormatter(console_formatter))
console_handler.setLevel(logging.INFO)
console_handler.setLevel(logging.DEBUG if options["debug"] else logging.INFO)
logger.addHandler(console_handler)
Expand All @@ -42,3 +43,29 @@ def set_logging_to_file(self, log_dir: str, timestamp: str, conf: dict):
file_handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s]: %(message)s"))
file_handler.setLevel(logging.DEBUG)
self.logger.addHandler(file_handler)


class CustomFormatter(logging.Formatter):
"""Class adding colours to console logger"""

def __init__(self, formatter):
super().__init__()
grey = "\x1b[0;38m"
light_green = "\x1b[1;32m"
yellow = "\x1b[0;33m"
red = "\x1b[0;31m"
light_red = "\x1b[1;31m"
reset = "\x1b[0m"

self.FORMATS = {
logging.DEBUG: light_green + formatter + reset,
logging.INFO: grey + formatter + reset,
logging.WARNING: yellow + formatter + reset,
logging.ERROR: red + formatter + reset,
logging.CRITICAL: light_red + formatter + reset
}

def format(self, record):
log_fmt = self.FORMATS.get(record.levelno)
formatter = logging.Formatter(log_fmt)
return formatter.format(record)
13 changes: 7 additions & 6 deletions source/modules/validators/validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import sys
import re
from ansible_deployer.modules.globalvars import SUBCOMMANDS
from ansible_deployer.modules.globalvars import SUBCOMMANDS, PRINT_FAIL, PRINT_END


class Validators:
Expand All @@ -15,7 +15,8 @@ def __init__(self, logger):
def verify_subcommand(command: str):
"""Function to check the first arguments for a valid subcommand"""
if command not in SUBCOMMANDS:
print("[CRITICAL]: Unknown subcommand :%s", (command), file=sys.stderr)
print(f"{PRINT_FAIL}[CRITICAL]: Unknown subcommand :%s {PRINT_END}", (command),
file=sys.stderr)
sys.exit("55")

@staticmethod
Expand All @@ -24,14 +25,14 @@ def verify_switches(switches: list):
Check if 2nd and following positional arguments are valid
"""
if switches[0] != "show" and len(switches[1:]) > 0:
print("[CRITICAL]: Too many positional arguments! Only subcommand \"show\" can accept"
" following arguments: task, infra.")
print(f"{PRINT_FAIL}[CRITICAL]: Too many positional arguments! Only subcommand \"show\""
f" can accept following arguments: task, infra.{PRINT_END}")
sys.exit("56")

for switch in switches[1:]:
if switch not in ("task", "infra"):
print(f"[CRITICAL]: Invalid argument {switch}! Subcommand \"show\" can accept only"
" following arguments: task, infra.")
print(f"{PRINT_FAIL}[CRITICAL]: Invalid argument {switch}! Subcommand \"show\" can"
f" accept only following arguments: task, infra.{PRINT_END}")
sys.exit("57")

def validate_options(self, options: dict):
Expand Down

0 comments on commit 4799820

Please sign in to comment.