Skip to content

Commit 3cf8570

Browse files
SCANPY-135 Add log messages through the code (#175)
1 parent 7289d73 commit 3cf8570

12 files changed

+56
-14
lines changed

src/pysonar_scanner/__main__.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
1919
#
2020

21+
import logging
2122
from pysonar_scanner import app_logging
2223
from pysonar_scanner import cache
2324
from pysonar_scanner import exceptions
@@ -48,7 +49,7 @@ def scan():
4849

4950
def do_scan():
5051
app_logging.setup()
51-
52+
logging.info("Starting Pysonar, the Sonar scanner CLI for Python")
5253
config = ConfigurationLoader.load()
5354
set_logging_options(config)
5455

@@ -57,10 +58,12 @@ def do_scan():
5758
api = build_api(config)
5859
check_version(api)
5960
update_config_with_api_urls(config, api.base_urls)
61+
logging.debug(f"Final loaded configuration: {config}")
6062

6163
cache_manager = cache.get_cache(config)
6264
scanner = create_scanner_engine(api, cache_manager, config)
6365

66+
logging.info("Starting the analysis...")
6467
return scanner.run(config)
6568

6669

@@ -76,8 +79,11 @@ def build_api(config: dict[str, any]) -> SonarQubeApi:
7679

7780
def check_version(api: SonarQubeApi):
7881
if api.is_sonar_qube_cloud():
82+
logging.debug(f"SonarQube Cloud url: {api.base_urls.base_url}")
7983
return
8084
version = api.get_analysis_version()
85+
logging.debug(f"SonarQube url: {api.base_urls.base_url}")
86+
8187
if not version.does_support_bootstrapping():
8288
raise SQTooOldException(
8389
f"This scanner only supports SonarQube versions >= {MIN_SUPPORTED_SQ_VERSION}. \n"
@@ -97,6 +103,7 @@ def update_config_with_api_urls(config, base_urls: BaseUrls):
97103
def create_scanner_engine(api, cache_manager, config):
98104
jre_path = create_jre(api, cache_manager, config)
99105
config[SONAR_SCANNER_JAVA_EXE_PATH] = str(jre_path.path)
106+
logging.debug(f"JRE path: {jre_path.path}")
100107
scanner_engine_path = ScannerEngineProvisioner(api, cache_manager).provision()
101108
scanner = ScannerEngine(jre_path, scanner_engine_path)
102109
return scanner

src/pysonar_scanner/api.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
import requests
2525
import requests.auth
2626

27+
from pysonar_scanner import app_logging
2728
from pysonar_scanner.configuration.properties import (
2829
SONAR_HOST_URL,
2930
SONAR_SCANNER_SONARCLOUD_URL,
@@ -231,7 +232,6 @@ def download_analysis_engine(self, handle: typing.BinaryIO) -> None:
231232
This method can raise a SonarQubeApiException if the server doesn't respond successfully.
232233
Alternative, if the file IO fails, an IOError or OSError can be raised.
233234
"""
234-
235235
try:
236236
res = requests.get(
237237
f"{self.base_urls.api_base_url}/analysis/engine",

src/pysonar_scanner/configuration/cli.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
#
2020
import argparse
2121

22+
from pysonar_scanner import app_logging
2223
from pysonar_scanner.configuration import properties
2324
from pysonar_scanner.exceptions import UnexpectedCliArgument
2425

src/pysonar_scanner/configuration/configuration_loader.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,10 @@
1717
# along with this program; if not, write to the Free Software Foundation,
1818
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
1919
#
20+
import logging
2021
from pathlib import Path
2122

23+
from pysonar_scanner import app_logging
2224
from pysonar_scanner.configuration.cli import CliConfigurationLoader
2325
from pysonar_scanner.configuration.pyproject_toml import TomlConfigurationLoader
2426
from pysonar_scanner.configuration.properties import SONAR_PROJECT_KEY, SONAR_TOKEN, SONAR_PROJECT_BASE_DIR, Key
@@ -35,6 +37,8 @@ def get_static_default_properties() -> dict[Key, any]:
3537
class ConfigurationLoader:
3638
@staticmethod
3739
def load() -> dict[Key, any]:
40+
logging.debug("Loading configuration properties...")
41+
3842
# each property loader is required to return NO default values.
3943
# E.g. if no property has been set, an empty dict must be returned.
4044
# Default values should be set through the get_static_default_properties() method

src/pysonar_scanner/configuration/environment_variables.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,12 @@
1717
# along with this program; if not, write to the Free Software Foundation,
1818
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
1919
#
20+
import logging
2021
import os
2122
import json
2223
from typing import Dict
2324

25+
from pysonar_scanner import app_logging
2426
from pysonar_scanner.configuration.properties import Key, PROPERTIES
2527

2628

@@ -48,10 +50,11 @@ def load_json_env_variables():
4850
json_params = os.environ["SONAR_SCANNER_JSON_PARAMS"]
4951
json_properties = json.loads(json_params)
5052
properties.update(json_properties)
51-
except json.JSONDecodeError:
52-
# If JSON is invalid, continue with regular environment variables
53-
# SCANPY-135 should log the error
54-
pass
53+
except json.JSONDecodeError as e:
54+
logging.warning(
55+
f"The JSON in SONAR_SCANNER_JSON_PARAMS environment variable is invalid. The other environment variables will still be loaded. Error : {e}"
56+
)
57+
logging.debug("Loaded environment properties: " + ", ".join(f"{key}={value}" for key, value in properties.items()))
5558
return properties
5659

5760

src/pysonar_scanner/configuration/pyproject_toml.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,11 @@
1717
# along with this program; if not, write to the Free Software Foundation,
1818
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
1919
#
20+
import logging
2021
from pathlib import Path
2122
from typing import Dict
2223
import os
24+
from pysonar_scanner import app_logging
2325
import tomli
2426

2527
from pysonar_scanner.configuration import properties
@@ -39,8 +41,9 @@ class TomlConfigurationLoader:
3941
def load(base_dir: Path) -> TomlProperties:
4042
filepath = base_dir / "pyproject.toml"
4143
if not os.path.isfile(filepath):
44+
logging.debug(f"No pyproject.toml at {filepath}")
4245
return TomlProperties({}, {})
43-
46+
logging.debug(f"pyproject.toml loaded from {filepath}")
4447
try:
4548
with open(filepath, "rb") as f:
4649
toml_dict = tomli.load(f)
@@ -49,9 +52,10 @@ def load(base_dir: Path) -> TomlProperties:
4952
# Look for general project configuration
5053
project_properties = TomlConfigurationLoader.__read_project_properties(toml_dict)
5154
return TomlProperties(sonar_properties, project_properties)
52-
except Exception:
53-
# If there's any error parsing the TOML file, return empty TomlProperties
54-
# SCANPY-135: We should log the pyproject.toml parsing error
55+
except Exception as e:
56+
logging.warning(
57+
f"There was an error reading the pyproject.toml file. No properties from the TOML file were extracted. Error: {e}"
58+
)
5559
return TomlProperties({}, {})
5660

5761
@staticmethod

src/pysonar_scanner/configuration/sonar_project_properties.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
# along with this program; if not, write to the Free Software Foundation,
1818
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
1919
#
20+
import logging
2021
from pathlib import Path
2122
from typing import Dict
2223
import os
@@ -26,8 +27,10 @@
2627
def load(base_dir: Path) -> Dict[str, str]:
2728
filepath = base_dir / "sonar-project.properties"
2829
if not os.path.isfile(filepath):
30+
logging.debug(f"no sonar-project.properties file found at {filepath}")
2931
return {}
3032

33+
logging.debug(f"sonar-project.properties loaded from {filepath}")
3134
props = Properties()
3235
with open(filepath, "rb") as f:
3336
props.load(f)

src/pysonar_scanner/jre.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
# along with this program; if not, write to the Free Software Foundation,
1818
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
1919
#
20+
import logging
2021
import pathlib
2122
import shutil
2223
import tarfile
@@ -67,6 +68,7 @@ def provision(self) -> JREResolvedPath:
6768
def __attempt_provisioning_jre_with_retry(self) -> tuple[JRE, pathlib.Path]:
6869
jre_and_resolved_path = self.__attempt_provisioning_jre()
6970
if jre_and_resolved_path is None:
71+
logging.warning("Something went wrong while provisionning the JRE. Retrying...")
7072
jre_and_resolved_path = self.__attempt_provisioning_jre()
7173
if jre_and_resolved_path is None:
7274
raise ChecksumException.create("JRE")

src/pysonar_scanner/scannerengine.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
from threading import Thread
2626
from typing import IO, Callable, Optional
2727

28+
from pysonar_scanner import app_logging
2829
from pysonar_scanner.api import SonarQubeApi
2930
from pysonar_scanner.cache import Cache, CacheFile
3031
from pysonar_scanner.exceptions import ChecksumException
@@ -115,6 +116,7 @@ def provision(self) -> pathlib.Path:
115116
if scanner_file is not None:
116117
return scanner_file.filepath
117118
# Retry once in case the checksum failed due to the scanner engine being updated between getting the checksum and downloading the jar
119+
logging.warning("Something went wrong while downloading the scanner engine. Retrying...")
118120
scanner_file = self.__download_and_verify()
119121
if scanner_file is not None:
120122
return scanner_file.filepath
@@ -125,6 +127,7 @@ def __download_and_verify(self) -> Optional[CacheFile]:
125127
engine_info = self.api.get_analysis_engine()
126128
cache_file = self.cache.get_file(engine_info.filename, engine_info.sha256)
127129
if not cache_file.is_valid():
130+
logging.debug("No valid cached analysis engine jar was found")
128131
self.__download_scanner_engine(cache_file)
129132
return cache_file if cache_file.is_valid() else None
130133

@@ -140,7 +143,9 @@ def __init__(self, jre_path: JREResolvedPath, scanner_engine_path: pathlib.Path)
140143

141144
def run(self, config: dict[str, any]):
142145
cmd = self.__build_command(self.jre_path, self.scanner_engine_path)
146+
logging.debug(f"Command: {cmd}")
143147
properties_str = self.__config_to_json(config)
148+
logging.debug(f"Properties: {properties_str}")
144149
return CmdExecutor(cmd, properties_str).execute()
145150

146151
def __build_command(self, jre_path: JREResolvedPath, scanner_engine_path: pathlib.Path) -> list[str]:

tests/test_environment_variables.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@
1717
# along with this program; if not, write to the Free Software Foundation,
1818
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
1919
#
20+
from json import JSONDecodeError
2021
import unittest
21-
from unittest.mock import patch
22+
from unittest.mock import MagicMock, patch
2223

2324
from pysonar_scanner.configuration import environment_variables
2425
from pysonar_scanner.configuration.properties import (
@@ -105,13 +106,19 @@ def test_environment_variables_from_json_params(self):
105106
self.assertEqual(len(properties), 2)
106107
self.assertDictEqual(properties, expected_properties)
107108

108-
def test_invalid_json_params(self):
109+
@patch("pysonar_scanner.configuration.environment_variables.logging")
110+
def test_invalid_json_params(self, mock_logging):
111+
109112
env = {"SONAR_SCANNER_JSON_PARAMS": '{"sonar.token": "json-token"'}
110113
with patch.dict("os.environ", env, clear=True):
111114
properties = environment_variables.load()
112115
self.assertEqual(len(properties), 0)
113116
self.assertDictEqual(properties, {})
114117

118+
mock_logging.warning.assert_called_once_with(
119+
"The JSON in SONAR_SCANNER_JSON_PARAMS environment variable is invalid. The other environment variables will still be loaded. Error : Expecting ',' delimiter: line 1 column 29 (char 28)",
120+
)
121+
115122
def test_environment_variables_priority_over_json_params(self):
116123
env = {
117124
"SONAR_TOKEN": "regular-token", # This should take priority

0 commit comments

Comments
 (0)