Skip to content

Commit

Permalink
Add log messages which are captured by the CI (#904)
Browse files Browse the repository at this point in the history
If gcovr is executed in Azure pipeline or GitHub actions a additional
logging handler is installed which prints warning and error  message
in a format detected by the CI system.
  • Loading branch information
Spacetown committed Mar 23, 2024
1 parent 9c1ffff commit 2e384b7
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 28 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Expand Up @@ -12,6 +12,8 @@ Breaking changes:

New features and notable changes:

- In Azure pipelines or GitHub actions errors and warnings are printed in an additional format captured by the CI. (:issue:`904`)

Bug fixes and small improvements:

Documentation:
Expand Down
7 changes: 2 additions & 5 deletions gcovr/__main__.py
Expand Up @@ -43,7 +43,7 @@
AlwaysMatchFilter,
DirectoryPrefixFilter,
configure_logging,
update_logging_formatter,
update_logging,
)
from .version import __version__
from .coverage import CovData, SummarizedStats
Expand Down Expand Up @@ -221,10 +221,7 @@ def main(args=None):
options = merge_options_and_set_defaults([cfg_options, cli_options.__dict__])

# Reconfigure the logging.
update_logging_formatter(options)

if options.verbose:
LOGGER.setLevel(logging.DEBUG)
update_logging(options)

if options.sort_branches and options.sort_key not in [
"uncovered-number",
Expand Down
72 changes: 53 additions & 19 deletions gcovr/utils.py
Expand Up @@ -32,10 +32,13 @@
from gcovr.options import Options

LOGGER = logging.getLogger("gcovr")
DEFAULT_LOGGING_HANDLER = logging.StreamHandler(sys.stderr)


LOG_FORMAT = "%(log_color)s(%(levelname)s) %(message)s"
LOG_FORMAT_THREADS = "%(log_color)s(%(levelname)s) - %(threadName)s - %(message)s"
LOG_FORMAT = "(%(levelname)s) %(message)s"
LOG_FORMAT_THREADS = "(%(levelname)s) - %(threadName)s - %(message)s"
COLOR_LOG_FORMAT = f"%(log_color)s{LOG_FORMAT}"
COLOR_LOG_FORMAT_THREADS = f"%(log_color)s{LOG_FORMAT_THREADS}"


class LoopChecker(object):
Expand Down Expand Up @@ -280,13 +283,15 @@ def match(self, path: str):
return super().match(path)


def __colored_formatter(options: Options) -> ColoredFormatter:
def __colored_formatter(options: Options = None) -> ColoredFormatter:
if options is not None:
log_format = LOG_FORMAT_THREADS if options.gcov_parallel > 1 else LOG_FORMAT
log_format = (
COLOR_LOG_FORMAT_THREADS if options.gcov_parallel > 1 else COLOR_LOG_FORMAT
)
force_color = getattr(options, "force_color", False)
no_color = getattr(options, "no_color", False)
else:
log_format = LOG_FORMAT
log_format = COLOR_LOG_FORMAT
force_color = False
no_color = False

Expand All @@ -309,14 +314,43 @@ def __colored_formatter(options: Options) -> ColoredFormatter:
)


def configure_logging(options: Options = None) -> None:
stream_handler = logging.StreamHandler(sys.stderr)
stream_handler.setFormatter(__colored_formatter(options))

logging.basicConfig(
handlers=[stream_handler],
level=logging.INFO,
)
def configure_logging() -> None:
logging.basicConfig(level=logging.INFO)
DEFAULT_LOGGING_HANDLER.setFormatter(__colored_formatter())
logging.getLogger().addHandler(DEFAULT_LOGGING_HANDLER)
ci_logging_prefixes = None
if "TF_BUILD" in os.environ:
ci_logging_prefixes = {
logging.WARNING: "##vso[task.logissue type=warning]",
logging.ERROR: "##vso[task.logissue type=error]",
}
elif "GITHUB_ACTIONS" in os.environ:
ci_logging_prefixes = {
logging.WARNING: "::warning::",
logging.ERROR: "::error::",
}

if ci_logging_prefixes is not None:

class CiFormatter(logging.Formatter):
"""Formatter to format messages to be captured in Azure"""

def __init__(self):
super(CiFormatter, self).__init__(fmt=LOG_FORMAT)

def format(self, record):
if record.levelno in ci_logging_prefixes:
result = (
f"{ci_logging_prefixes[record.levelno]}{super().format(record)}"
)
else:
result = ""

return result

handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(CiFormatter())
logging.getLogger().addHandler(handler)

def exception_hook(exc_type, exc_value, exc_traceback) -> None:
logging.exception(
Expand All @@ -326,12 +360,12 @@ def exception_hook(exc_type, exc_value, exc_traceback) -> None:
sys.excepthook = exception_hook


def update_logging_formatter(options: Options) -> None:
# The one and only LOGGER was configured from ourselve.
if len(logging.getLogger().handlers) == 1 and (
logging.getLogger().handlers[0].formatter._fmt == LOG_FORMAT
):
logging.getLogger().handlers[0].setFormatter(__colored_formatter(options))
def update_logging(options: Options) -> None:
if options.verbose:
LOGGER.setLevel(logging.DEBUG)

# Update the formatter of the default logger depending on options
DEFAULT_LOGGING_HANDLER.setFormatter(__colored_formatter(options))


@contextmanager
Expand Down
8 changes: 4 additions & 4 deletions tests/simple1/Makefile
Expand Up @@ -12,10 +12,10 @@ run: txt clover cobertura html sonarqube jacoco json json_summary coveralls
txt:
./testcase
# a couple of tests about failure thresholds
$(GCOVR) --fail-under-line 80.1 --print-summary 2>fail_under.stderr; test $$? -eq 2 || ( cat fail_under.stderr & exit 1 )
grep -F "failed minimum line coverage" fail_under.stderr
$(GCOVR) --fail-under-branch 50.1 --print-summary 2>fail_under.stderr; test $$? -eq 4 || ( cat fail_under.stderr & exit 1 )
grep -F "failed minimum branch coverage" fail_under.stderr
TF_BUILD=true $(GCOVR) --fail-under-line 80.1 --print-summary 2>fail_under.stderr; test $$? -eq 2 || ( cat fail_under.stderr & exit 1 )
grep -F "##vso[task.logissue type=error](ERROR) failed minimum line coverage" fail_under.stderr
GITHUB_ACTIONS=true $(GCOVR) --fail-under-branch 50.1 --print-summary 2>fail_under.stderr; test $$? -eq 4 || ( cat fail_under.stderr & exit 1 )
grep -F "::error::(ERROR) failed minimum branch coverage" fail_under.stderr
$(GCOVR) --decision --fail-under-decision 50.1 --print-summary 2>fail_under.stderr; test $$? -eq 8 || ( cat fail_under.stderr & exit 1 )
grep -F "failed minimum decision coverage" fail_under.stderr
$(GCOVR) --fail-under-function 100 --print-summary 2>fail_under.stderr; test $$? -eq 16 || ( cat fail_under.stderr & exit 1 )
Expand Down

0 comments on commit 2e384b7

Please sign in to comment.