Skip to content

Commit a74fe49

Browse files
userleruedaimheresamir
authored andcommitted
Fix logger to allow application consuming library to set logging level
1 parent be32874 commit a74fe49

File tree

7 files changed

+28
-15
lines changed

7 files changed

+28
-15
lines changed

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
66

77
## [Unreleased]
88

9+
## [0.1.5] - 2025-05-01
10+
11+
### Added
12+
- Add support for configuring an external logger
13+
[cyberark/conjur-api-python#54](https://github.com/cyberark/conjur-api-python/issues/54), CNJR-9408
14+
915
## [0.1.4] - 2025-03-26
1016

1117
### Fixed

conjur_api/client.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
LOGGING_FORMAT = '%(asctime)s %(levelname)s: %(message)s'
2626
LOGGING_FORMAT_WARNING = 'WARNING: %(message)s'
2727

28+
logger = logging.getLogger(__name__)
2829

2930
@allow_sync_invocation()
3031
# pylint: disable=too-many-public-methods
@@ -86,18 +87,18 @@ def __init__(
8687
self.async_mode = async_mode
8788
if ssl_verification_mode == SslVerificationMode.INSECURE:
8889
# TODO remove this is a cli user facing
89-
logging.debug("Warning: Running the command with '--insecure' "
90+
logger.debug("Warning: Running the command with '--insecure' "
9091
"makes your system vulnerable to security attacks")
9192

92-
logging.debug("Initializing configuration...")
93+
logger.debug("Initializing configuration...")
9394

9495
self.ssl_verification_mode = ssl_verification_mode
9596
self.connection_info = connection_info
9697
self.debug = debug
9798
self._api = self._create_api(http_debug, authn_strategy)
9899

99100
self.set_telemetry_header()
100-
logging.debug("Client initialized")
101+
logger.debug("Client initialized")
101102

102103
def set_integration_name( self, value ):
103104
"""

conjur_api/http/api.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from conjur_api.wrappers.http_response import HttpResponse
2323
from conjur_api.wrappers.http_wrapper import HttpVerb, invoke_endpoint
2424

25+
logger = logging.getLogger(__name__)
2526

2627
# pylint: disable=unspecified-encoding,too-many-public-methods
2728
class Api:
@@ -83,11 +84,11 @@ async def api_token(self) -> str:
8384
@return: Conjur api_token
8485
"""
8586
if not self._api_token or datetime.now() > self.api_token_expiration:
86-
logging.debug("API token missing or expired. Fetching new one...")
87+
logger.debug("API token missing or expired. Fetching new one...")
8788
self._api_token, self.api_token_expiration = await self.authenticate()
8889
return self._api_token
8990

90-
logging.debug("Using cached API token...")
91+
logger.debug("Using cached API token...")
9192
return self._api_token
9293

9394
async def login(self) -> str:
@@ -176,7 +177,7 @@ async def check_privilege(self, kind: str, resource_id: str, privilege: str, rol
176177
api_token=await self.api_token,
177178
ssl_verification_metadata=self.ssl_verification_data,
178179
proxy_params=self._connection_info.proxy_params)
179-
logging.debug(str(response))
180+
logger.debug(str(response))
180181
except HttpStatusError as err:
181182
if err.status == 404:
182183
return False

conjur_api/http/ssl/ssl_context_factory.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
from conjur_api.models.enums.os_types import OSTypes
1919
from conjur_api.utils.util_functions import get_current_os
2020

21+
logger = logging.getLogger(__name__)
2122

2223
# pylint: disable=too-few-public-methods
2324
def create_ssl_context(ssl_verification_metadata: SslVerificationMetadata) -> ssl.SSLContext:
@@ -29,7 +30,7 @@ def create_ssl_context(ssl_verification_metadata: SslVerificationMetadata) -> ss
2930
os_type = get_current_os()
3031

3132
if ssl_verification_metadata.mode == SslVerificationMode.TRUST_STORE:
32-
logging.debug("Creating SSLContext from OS TrustStore for '%s'", os_type.name)
33+
logger.debug("Creating SSLContext from OS TrustStore for '%s'", os_type.name)
3334
ssl_context = _create_ssl_context(os_type)
3435
else:
3536
ssl_context = ssl.create_default_context(cafile=ssl_verification_metadata.ca_cert_path)
@@ -39,7 +40,7 @@ def create_ssl_context(ssl_verification_metadata: SslVerificationMetadata) -> ss
3940
# pylint: disable=no-member
4041
ssl_context.verify_flags |= ssl.OP_NO_TICKET
4142

42-
logging.debug("SSLContext created successfully")
43+
logger.debug("SSLContext created successfully")
4344

4445
return ssl_context
4546

@@ -76,7 +77,7 @@ def _get_mac_ca_certs() -> str:
7677
Get Root CAs from Mac Keychain.
7778
@return: String containing trusted root CAs from the keychain.
7879
"""
79-
logging.debug("Get CA certs from Mac keychain")
80+
logger.debug("Get CA certs from Mac keychain")
8081
try:
8182
get_ca_certs_process = subprocess.run(
8283
["security", "find-certificate", "-a", "-p", "/System/Library/Keychains/SystemRootCertificates.keychain"],

conjur_api/providers/authn_authentication_strategy.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
API_TOKEN_SAFETY_BUFFER = 3
2424
DEFAULT_API_TOKEN_DURATION = DEFAULT_TOKEN_EXPIRATION - API_TOKEN_SAFETY_BUFFER
2525

26+
logger = logging.getLogger(__name__)
2627

2728
class AuthnAuthenticationStrategy(AuthenticationStrategyInterface):
2829
"""
@@ -41,7 +42,7 @@ async def login(self, connection_info: ConjurConnectionInfo, ssl_verification_da
4142
Login uses a username and password to fetch a long-lived conjur_api token
4243
"""
4344

44-
logging.debug("Logging in to %s...", connection_info.conjur_url)
45+
logger.debug("Logging in to %s...", connection_info.conjur_url)
4546
creds = self._retrieve_credential_data(connection_info.conjur_url)
4647

4748
if not creds.password:
@@ -55,7 +56,7 @@ async def authenticate(self, connection_info, ssl_verification_data) -> Tuple[st
5556
Authenticate uses the api_key (retrieved in `login()`) to fetch a short-lived conjur_api token that
5657
for a limited time will allow you to interact fully with the Conjur vault.
5758
"""
58-
logging.debug("Authenticating to %s...", connection_info.conjur_url)
59+
logger.debug("Authenticating to %s...", connection_info.conjur_url)
5960
creds = self._retrieve_credential_data(connection_info.conjur_url)
6061

6162
# If the credential provider already has a valid API token, return it
@@ -69,7 +70,7 @@ async def authenticate(self, connection_info, ssl_verification_data) -> Tuple[st
6970

7071
def _retrieve_credential_data(self, url: str) -> CredentialsData:
7172
credential_location = self._credentials_provider.get_store_location()
72-
logging.debug("Retrieving credentials from the '%s'...", credential_location)
73+
logger.debug("Retrieving credentials from the '%s'...", credential_location)
7374

7475
return self._credentials_provider.load(url)
7576

conjur_api/providers/jwt_authentication_strategy.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525
API_TOKEN_SAFETY_BUFFER = 3
2626
DEFAULT_API_TOKEN_DURATION = DEFAULT_TOKEN_EXPIRATION - API_TOKEN_SAFETY_BUFFER
2727

28+
logger = logging.getLogger(__name__)
29+
2830
class JWTAuthenticationStrategy(AuthenticationStrategyInterface):
2931
"""
3032
JWTAuthenticationStrategy
@@ -49,7 +51,7 @@ async def authenticate(
4951
Authenticate method makes a POST request to the authentication endpoint,
5052
retrieves a token, and calculates the token expiration.
5153
"""
52-
logging.debug("Authenticating to %s...", connection_info.conjur_url)
54+
logger.debug("Authenticating to %s...", connection_info.conjur_url)
5355

5456
api_token = await self._send_authenticate_request(ssl_verification_data, connection_info)
5557

conjur_api/utils/decorators.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import asyncio
99
from conjur_api.errors.errors import SyncInvocationInsideEventLoopError
1010

11+
logger = logging.getLogger(__name__)
1112

1213
def allow_sync_invocation():
1314
"""
@@ -23,7 +24,7 @@ def wrapper(self, *args):
2324
return func(self, *args)
2425
loop = _get_event_loop()
2526
if loop is not None and loop.is_running():
26-
logging.error(
27+
logger.error(
2728
"Failed to run conjur_api %s function in sync mode "
2829
"because code is running inside event loop", func.__name__)
2930
raise SyncInvocationInsideEventLoopError()
@@ -45,5 +46,5 @@ def _get_event_loop():
4546
except RuntimeError: # No loop exist
4647
return None
4748
except Exception as err:
48-
logging.error("Couldn't get event loop for unknown reason. details: %s", err)
49+
logger.error("Couldn't get event loop for unknown reason. details: %s", err)
4950
raise

0 commit comments

Comments
 (0)