mirror of
https://github.com/kevingruesser/bootstrap-vz.git
synced 2025-08-22 09:50:37 +00:00
Support --color option to indicate whether to use colors in the terminal
Mimic the behavior of the --color=<auto|always|never> found in tools like `ls' and `grep'. Default to `auto' which checks whether stderr is a tty to define whether colors are used. Tested: - Ran ./boostrap-vz --color=never and --color=always, confirmed colorization worked as expected. - Ran ./boostrap-vz --color=auto ${manifest_file} 2>bootstrap.log, confirmed colors were not added to boostrap.log by default, repeated the test with --color=always and confirmed escape sequences were output. Signed-off-by: Filipe Brandenburger <filbranden@google.com>
This commit is contained in:
parent
2628007839
commit
84cf497c66
2 changed files with 16 additions and 4 deletions
|
@ -4,18 +4,20 @@ both to a file and to the console.
|
|||
import logging
|
||||
|
||||
|
||||
def get_console_handler(debug):
|
||||
def get_console_handler(debug, colorize):
|
||||
"""Returns a log handler for the console
|
||||
The handler color codes the different log levels
|
||||
|
||||
:params bool debug: Whether to set the log level to DEBUG (otherwise INFO)
|
||||
:params bool colorize: Whether to colorize console output
|
||||
:return: The console logging handler
|
||||
"""
|
||||
# Create a console log handler
|
||||
import sys
|
||||
console_handler = logging.StreamHandler(sys.stderr)
|
||||
# We want to colorize the output to the console, so we add a formatter
|
||||
console_handler.setFormatter(ConsoleFormatter())
|
||||
if colorize:
|
||||
# We want to colorize the output to the console, so we add a formatter
|
||||
console_handler.setFormatter(ConsoleFormatter())
|
||||
# Set the log level depending on the debug argument
|
||||
if debug:
|
||||
console_handler.setLevel(logging.DEBUG)
|
||||
|
|
|
@ -44,6 +44,8 @@ Options:
|
|||
If <path> is `-' file logging will be disabled.
|
||||
--pause-on-error Pause on error, before rollback
|
||||
--dry-run Don't actually run the tasks
|
||||
--color=auto|always|never
|
||||
Colorize the console output [default: auto]
|
||||
--debug Print debugging information
|
||||
-h, --help show this help
|
||||
"""
|
||||
|
@ -68,7 +70,15 @@ def setup_loggers(opts):
|
|||
file_handler = log.get_file_handler(path=logpath, debug=True)
|
||||
root.addHandler(file_handler)
|
||||
|
||||
console_handler = log.get_console_handler(debug=opts['--debug'])
|
||||
if opts['--color'] == 'never':
|
||||
colorize = False
|
||||
elif opts['--color'] == 'always':
|
||||
colorize = True
|
||||
else:
|
||||
# If --color=auto (default), decide whether to colorize by whether stderr is a tty.
|
||||
import os
|
||||
colorize = os.isatty(2)
|
||||
console_handler = log.get_console_handler(debug=opts['--debug'], colorize=colorize)
|
||||
root.addHandler(console_handler)
|
||||
|
||||
|
||||
|
|
Loading…
Add table
Reference in a new issue