Skip to content
This repository was archived by the owner on Dec 5, 2025. It is now read-only.

Commit 1662377

Browse files
authored
[client] Improve logging (#303)
1 parent ff21233 commit 1662377

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

45 files changed

+723
-1149
lines changed

pycti/api/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import logging
2+
3+
LOGGER = logging.getLogger(__name__)

pycti/api/opencti_api_client.py

Lines changed: 16 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import urllib3
1212
from pythonjsonlogger import jsonlogger
1313

14+
from pycti.api import LOGGER
1415
from pycti.api.opencti_api_connector import OpenCTIApiConnector
1516
from pycti.api.opencti_api_work import OpenCTIApiWork
1617
from pycti.entities.opencti_attack_pattern import AttackPattern
@@ -124,21 +125,19 @@ def __init__(
124125
raise ValueError("A TOKEN must be set")
125126

126127
# Configure logger
127-
self.log_level = log_level
128-
numeric_level = getattr(logging, self.log_level.upper(), None)
129-
if not isinstance(numeric_level, int):
130-
raise ValueError("Invalid log level: " + self.log_level)
128+
log_level = log_level.upper()
129+
LOGGER.setLevel(log_level)
131130

132131
if json_logging:
133132
log_handler = logging.StreamHandler()
134-
log_handler.setLevel(self.log_level.upper())
133+
log_handler.setLevel(log_level)
135134
formatter = CustomJsonFormatter(
136135
"%(timestamp)s %(level)s %(name)s %(message)s"
137136
)
138137
log_handler.setFormatter(formatter)
139-
logging.basicConfig(handlers=[log_handler], level=numeric_level, force=True)
138+
logging.basicConfig(handlers=[log_handler], level=log_level, force=True)
140139
else:
141-
logging.basicConfig(level=numeric_level)
140+
logging.basicConfig(level=log_level)
142141

143142
# Define API
144143
self.api_token = token
@@ -328,19 +327,19 @@ def query(self, query, variables={}):
328327
else main_error["message"]
329328
)
330329
if "data" in main_error and "reason" in main_error["data"]:
331-
logging.error(main_error["data"]["reason"])
330+
LOGGER.error(main_error["data"]["reason"])
332331
raise ValueError(
333332
{"name": error_name, "message": main_error["data"]["reason"]}
334333
)
335334
else:
336-
logging.error(main_error["message"])
335+
LOGGER.error(main_error["message"])
337336
raise ValueError(
338337
{"name": error_name, "message": main_error["message"]}
339338
)
340339
else:
341340
return result
342341
else:
343-
logging.info(r.text)
342+
LOGGER.info(r.text)
344343
raise ValueError(r.text)
345344

346345
def fetch_opencti_file(self, fetch_uri, binary=False, serialize=False):
@@ -363,24 +362,6 @@ def fetch_opencti_file(self, fetch_uri, binary=False, serialize=False):
363362
return base64.b64encode(r.text).decode("utf-8")
364363
return r.text
365364

366-
def log(self, level, message):
367-
"""log a message with defined log level
368-
369-
:param level: must be a valid logging log level (debug, info, warning, error)
370-
:type level: str
371-
:param message: the message to log
372-
:type message: str
373-
"""
374-
375-
if level == "debug":
376-
logging.debug(message)
377-
elif level == "info":
378-
logging.info(message)
379-
elif level == "warning":
380-
logging.warn(message)
381-
elif level == "error":
382-
logging.error(message)
383-
384365
def health_check(self):
385366
"""submit an example request to the OpenCTI API.
386367
@@ -402,7 +383,7 @@ def get_logs_worker_config(self):
402383
rtype: dict
403384
"""
404385

405-
logging.info("Getting logs worker config...")
386+
LOGGER.info("Getting logs worker config...")
406387
query = """
407388
query LogsWorkerConfig {
408389
logsWorkerConfig {
@@ -603,7 +584,7 @@ def upload_file(self, **kwargs):
603584
data = kwargs.get("data", None)
604585
mime_type = kwargs.get("mime_type", "text/plain")
605586
if file_name is not None:
606-
self.log("info", "Uploading a file.")
587+
LOGGER.info("Uploading a file.")
607588
query = """
608589
mutation UploadImport($file: Upload!) {
609590
uploadImport(file: $file) {
@@ -621,17 +602,14 @@ def upload_file(self, **kwargs):
621602

622603
return self.query(query, {"file": (File(file_name, data, mime_type))})
623604
else:
624-
self.log(
625-
"error",
626-
"[upload] Missing parameters: file_name or data",
627-
)
605+
LOGGER.error("[upload] Missing parameter: file_name")
628606
return None
629607

630608
def upload_pending_file(self, **kwargs):
631609
"""upload a file to OpenCTI API
632610
633611
:param `**kwargs`: arguments for file upload (required: `file_name` and `data`)
634-
:return: returns the query respons for the file upload
612+
:return: returns the query response for the file upload
635613
:rtype: dict
636614
"""
637615

@@ -641,7 +619,7 @@ def upload_pending_file(self, **kwargs):
641619
entity_id = kwargs.get("entity_id", None)
642620

643621
if file_name is not None:
644-
self.log("info", "Uploading a file.")
622+
LOGGER.info("Uploading a file.")
645623
query = """
646624
mutation UploadPending($file: Upload!, $entityId: String) {
647625
uploadPending(file: $file, entityId: $entityId) {
@@ -661,10 +639,7 @@ def upload_pending_file(self, **kwargs):
661639
{"file": (File(file_name, data, mime_type)), "entityId": entity_id},
662640
)
663641
else:
664-
self.log(
665-
"error",
666-
"[upload] Missing parameters: file_name or data",
667-
)
642+
LOGGER.error("[upload] Missing parameter: file_name")
668643
return None
669644

670645
def get_stix_content(self, id):
@@ -674,7 +649,7 @@ def get_stix_content(self, id):
674649
rtype: dict
675650
"""
676651

677-
logging.info("Entity in JSON " + id)
652+
LOGGER.info("Entity in JSON %s", id)
678653
query = """
679654
query StixQuery($id: String!) {
680655
stix(id: $id)

pycti/api/opencti_api_connector.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import json
2-
import logging
32
from typing import Any, Dict
43

4+
from pycti.api import LOGGER
55
from pycti.connector.opencti_connector import OpenCTIConnector
66

77

@@ -18,7 +18,7 @@ def list(self) -> Dict:
1818
:rtype: dict
1919
"""
2020

21-
logging.info("Getting connectors ...")
21+
LOGGER.info("Getting connectors ...")
2222
query = """
2323
query GetConnectors {
2424
connectorsForWorker {

pycti/api/opencti_api_work.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1-
import logging
21
import time
32
from typing import Dict, List
43

4+
from pycti.api import LOGGER
5+
56

67
class OpenCTIApiWork:
78
"""OpenCTIApiJob"""
@@ -10,7 +11,7 @@ def __init__(self, api):
1011
self.api = api
1112

1213
def to_received(self, work_id: str, message: str):
13-
logging.info("Reporting work update_received " + work_id)
14+
LOGGER.info("Reporting work update_received %s", work_id)
1415
query = """
1516
mutation workToReceived($id: ID!, $message: String) {
1617
workEdit(id: $id) {
@@ -21,7 +22,7 @@ def to_received(self, work_id: str, message: str):
2122
self.api.query(query, {"id": work_id, "message": message})
2223

2324
def to_processed(self, work_id: str, message: str, in_error: bool = False):
24-
logging.info("Reporting work update_received " + work_id)
25+
LOGGER.info("Reporting work update_received %s", work_id)
2526
query = """
2627
mutation workToProcessed($id: ID!, $message: String, $inError: Boolean) {
2728
workEdit(id: $id) {
@@ -32,7 +33,7 @@ def to_processed(self, work_id: str, message: str, in_error: bool = False):
3233
self.api.query(query, {"id": work_id, "message": message, "inError": in_error})
3334

3435
def ping(self, work_id: str):
35-
logging.info("Ping work " + work_id)
36+
LOGGER.info("Ping work %s", work_id)
3637
query = """
3738
mutation pingWork($id: ID!) {
3839
workEdit(id: $id) {
@@ -43,7 +44,7 @@ def ping(self, work_id: str):
4344
self.api.query(query, {"id": work_id})
4445

4546
def report_expectation(self, work_id: str, error):
46-
logging.info("Report expectation for " + work_id)
47+
LOGGER.info("Report expectation for %s", work_id)
4748
query = """
4849
mutation reportExpectation($id: ID!, $error: WorkErrorInput) {
4950
workEdit(id: $id) {
@@ -57,9 +58,7 @@ def report_expectation(self, work_id: str, error):
5758
self.api.log("error", "Cannot report expectation")
5859

5960
def add_expectations(self, work_id: str, expectations: int):
60-
logging.info(
61-
"Update action expectations " + work_id + " - " + str(expectations)
62-
)
61+
LOGGER.info("Update action expectations %s - %s", work_id, expectations)
6362
query = """
6463
mutation addExpectations($id: ID!, $expectations: Int) {
6564
workEdit(id: $id) {
@@ -73,7 +72,7 @@ def add_expectations(self, work_id: str, expectations: int):
7372
self.api.log("error", "Cannot report expectation")
7473

7574
def initiate_work(self, connector_id: str, friendly_name: str) -> str:
76-
logging.info("Initiate work for " + connector_id)
75+
LOGGER.info("Initiate work for %s", connector_id)
7776
query = """
7877
mutation workAdd($connectorId: String!, $friendlyName: String) {
7978
workAdd(connectorId: $connectorId, friendlyName: $friendlyName) {

pycti/connector/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import logging
2+
3+
LOGGER = logging.getLogger(__name__)

0 commit comments

Comments
 (0)