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

Commit 0829b0c

Browse files
[client] Global change of log management (#521)
1 parent aea3674 commit 0829b0c

File tree

61 files changed

+1223
-1022
lines changed

Some content is hidden

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

61 files changed

+1223
-1022
lines changed

pycti/api/__init__.py

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

pycti/api/opencti_api_client.py

Lines changed: 10 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,12 @@
33
import datetime
44
import io
55
import json
6-
import logging
76
from typing import Union
87

98
import magic
109
import requests
11-
import urllib3
12-
from pythonjsonlogger import jsonlogger
1310

1411
from pycti import __version__
15-
from pycti.api import LOGGER
1612
from pycti.api.opencti_api_connector import OpenCTIApiConnector
1713
from pycti.api.opencti_api_playbook import OpenCTIApiPlaybook
1814
from pycti.api.opencti_api_work import OpenCTIApiWork
@@ -65,24 +61,10 @@
6561
from pycti.entities.opencti_tool import Tool
6662
from pycti.entities.opencti_vocabulary import Vocabulary
6763
from pycti.entities.opencti_vulnerability import Vulnerability
64+
from pycti.utils.opencti_logger import logger
6865
from pycti.utils.opencti_stix2 import OpenCTIStix2
6966
from pycti.utils.opencti_stix2_utils import OpenCTIStix2Utils
7067

71-
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
72-
73-
74-
class CustomJsonFormatter(jsonlogger.JsonFormatter):
75-
def add_fields(self, log_record, record, message_dict):
76-
super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict)
77-
if not log_record.get("timestamp"):
78-
# This doesn't use record.created, so it is slightly off
79-
now = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%fZ")
80-
log_record["timestamp"] = now
81-
if log_record.get("level"):
82-
log_record["level"] = log_record["level"].upper()
83-
else:
84-
log_record["level"] = record.levelname
85-
8668

8769
class File:
8870
def __init__(self, name, data, mime="text/plain"):
@@ -141,19 +123,8 @@ def __init__(
141123
raise ValueError("A TOKEN must be set")
142124

143125
# Configure logger
144-
log_level = log_level.upper()
145-
LOGGER.setLevel(log_level)
146-
147-
if json_logging:
148-
log_handler = logging.StreamHandler()
149-
log_handler.setLevel(log_level)
150-
formatter = CustomJsonFormatter(
151-
"%(timestamp)s %(level)s %(name)s %(message)s"
152-
)
153-
log_handler.setFormatter(formatter)
154-
logging.basicConfig(handlers=[log_handler], level=log_level, force=True)
155-
else:
156-
logging.basicConfig(level=log_level)
126+
self.logger_class = logger(log_level.upper(), json_logging)
127+
self.app_logger = self.logger_class("api")
157128

158129
# Define API
159130
self.api_token = token
@@ -398,23 +369,6 @@ def fetch_opencti_file(self, fetch_uri, binary=False, serialize=False):
398369
return base64.b64encode(r.text).decode("utf-8")
399370
return r.text
400371

401-
def log(self, level, message):
402-
"""log a message with defined log level
403-
:param level: must be a valid logging log level (debug, info, warning, error)
404-
:type level: str
405-
:param message: the message to log
406-
:type message: str
407-
"""
408-
409-
if level == "debug":
410-
LOGGER.debug(message)
411-
elif level == "info":
412-
LOGGER.info(message)
413-
elif level == "warning":
414-
LOGGER.warning(message)
415-
elif level == "error":
416-
LOGGER.error(message)
417-
418372
def health_check(self):
419373
"""submit an example request to the OpenCTI API.
420374
@@ -426,7 +380,7 @@ def health_check(self):
426380
if test is not None:
427381
return True
428382
except Exception as err: # pylint: disable=broad-except
429-
LOGGER.error("%s", err)
383+
self.app_logger.error(str(err))
430384
return False
431385
return False
432386

@@ -437,7 +391,7 @@ def get_logs_worker_config(self):
437391
rtype: dict
438392
"""
439393

440-
LOGGER.info("Getting logs worker config...")
394+
self.app_logger.info("Getting logs worker config...")
441395
query = """
442396
query LogsWorkerConfig {
443397
logsWorkerConfig {
@@ -638,7 +592,7 @@ def upload_file(self, **kwargs):
638592
data = kwargs.get("data", None)
639593
mime_type = kwargs.get("mime_type", "text/plain")
640594
if file_name is not None:
641-
LOGGER.info("Uploading a file.")
595+
self.app_logger.info("Uploading a file.")
642596
query = """
643597
mutation UploadImport($file: Upload!) {
644598
uploadImport(file: $file) {
@@ -656,7 +610,7 @@ def upload_file(self, **kwargs):
656610

657611
return self.query(query, {"file": (File(file_name, data, mime_type))})
658612
else:
659-
LOGGER.error("[upload] Missing parameter: file_name")
613+
self.app_logger.error("[upload] Missing parameter: file_name")
660614
return None
661615

662616
def upload_pending_file(self, **kwargs):
@@ -673,7 +627,7 @@ def upload_pending_file(self, **kwargs):
673627
entity_id = kwargs.get("entity_id", None)
674628

675629
if file_name is not None:
676-
LOGGER.info("Uploading a file.")
630+
self.app_logger.info("Uploading a file.")
677631
query = """
678632
mutation UploadPending($file: Upload!, $entityId: String) {
679633
uploadPending(file: $file, entityId: $entityId) {
@@ -693,7 +647,7 @@ def upload_pending_file(self, **kwargs):
693647
{"file": (File(file_name, data, mime_type)), "entityId": entity_id},
694648
)
695649
else:
696-
LOGGER.error("[upload] Missing parameter: file_name")
650+
self.app_logger.error("[upload] Missing parameter: file_name")
697651
return None
698652

699653
def get_stix_content(self, id):
@@ -703,7 +657,7 @@ def get_stix_content(self, id):
703657
rtype: dict
704658
"""
705659

706-
LOGGER.info("Entity in JSON %s", id)
660+
self.app_logger.info("Entity in JSON", {"id": id})
707661
query = """
708662
query StixQuery($id: String!) {
709663
stix(id: $id)

pycti/api/opencti_api_connector.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import json
22
from typing import Any, Dict
33

4-
from pycti.api import LOGGER
54
from pycti.connector.opencti_connector import OpenCTIConnector
65

76

@@ -18,7 +17,7 @@ def list(self) -> Dict:
1817
:rtype: dict
1918
"""
2019

21-
LOGGER.info("Getting connectors ...")
20+
self.api.app_logger.info("Getting connectors ...")
2221
query = """
2322
query GetConnectors {
2423
connectorsForWorker {

pycti/api/opencti_api_playbook.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
1-
from pycti.api import LOGGER
2-
3-
41
class OpenCTIApiPlaybook:
52
"""OpenCTIApiPlaybook"""
63

74
def __init__(self, api):
85
self.api = api
96

107
def playbook_step_execution(self, playbook: dict, bundle: str):
11-
LOGGER.info("Executing playbook step %s", playbook["playbook_id"])
8+
self.api.app_logger.info("Executing playbook step", playbook["playbook_id"])
129
query = """
1310
mutation PlaybookStepExecution($execution_id: ID!, $execution_start: DateTime!, $data_instance_id: ID!, $playbook_id: ID!, $previous_step_id: ID!, $step_id: ID!, $previous_bundle: String!, $bundle: String!) {
1411
playbookStepExecution(execution_id: $execution_id, execution_start: $execution_start, data_instance_id: $data_instance_id, playbook_id: $playbook_id, previous_step_id: $previous_step_id, step_id: $step_id, previous_bundle: $previous_bundle, bundle: $bundle)

pycti/api/opencti_api_work.py

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
import time
22
from typing import Dict, List
33

4-
from pycti.api import LOGGER
5-
64

75
class OpenCTIApiWork:
86
"""OpenCTIApiJob"""
@@ -11,7 +9,7 @@ def __init__(self, api):
119
self.api = api
1210

1311
def to_received(self, work_id: str, message: str):
14-
LOGGER.info("Reporting work update_received %s", work_id)
12+
self.api.app_logger.info("Reporting work update_received", {"work_id": work_id})
1513
query = """
1614
mutation workToReceived($id: ID!, $message: String) {
1715
workEdit(id: $id) {
@@ -22,7 +20,9 @@ def to_received(self, work_id: str, message: str):
2220
self.api.query(query, {"id": work_id, "message": message})
2321

2422
def to_processed(self, work_id: str, message: str, in_error: bool = False):
25-
LOGGER.info("Reporting work update_processed %s", work_id)
23+
self.api.app_logger.info(
24+
"Reporting work update_processed", {"work_id": work_id}
25+
)
2626
query = """
2727
mutation workToProcessed($id: ID!, $message: String, $inError: Boolean) {
2828
workEdit(id: $id) {
@@ -33,7 +33,7 @@ def to_processed(self, work_id: str, message: str, in_error: bool = False):
3333
self.api.query(query, {"id": work_id, "message": message, "inError": in_error})
3434

3535
def ping(self, work_id: str):
36-
LOGGER.info("Ping work %s", work_id)
36+
self.api.app_logger.info("Ping work", {"work_id": work_id})
3737
query = """
3838
mutation pingWork($id: ID!) {
3939
workEdit(id: $id) {
@@ -44,7 +44,7 @@ def ping(self, work_id: str):
4444
self.api.query(query, {"id": work_id})
4545

4646
def report_expectation(self, work_id: str, error):
47-
LOGGER.info("Report expectation for %s", work_id)
47+
self.api.app_logger.info("Report expectation", {"work_id": work_id})
4848
query = """
4949
mutation reportExpectation($id: ID!, $error: WorkErrorInput) {
5050
workEdit(id: $id) {
@@ -55,10 +55,13 @@ def report_expectation(self, work_id: str, error):
5555
try:
5656
self.api.query(query, {"id": work_id, "error": error})
5757
except:
58-
self.api.log("error", "Cannot report expectation")
58+
self.api.app_logger.error("Cannot report expectation")
5959

6060
def add_expectations(self, work_id: str, expectations: int):
61-
LOGGER.info("Update action expectations %s - %s", work_id, expectations)
61+
self.api.app_logger.info(
62+
"Update action expectations",
63+
{"work_id": work_id, "expectations": expectations},
64+
)
6265
query = """
6366
mutation addExpectations($id: ID!, $expectations: Int) {
6467
workEdit(id: $id) {
@@ -69,10 +72,10 @@ def add_expectations(self, work_id: str, expectations: int):
6972
try:
7073
self.api.query(query, {"id": work_id, "expectations": expectations})
7174
except:
72-
self.api.log("error", "Cannot report expectation")
75+
self.api.app_logger.error("Cannot report expectation")
7376

7477
def initiate_work(self, connector_id: str, friendly_name: str) -> str:
75-
LOGGER.info("Initiate work for %s", connector_id)
78+
self.api.app_logger.info("Initiate work", {"connector_id": connector_id})
7679
query = """
7780
mutation workAdd($connectorId: String!, $friendlyName: String) {
7881
workAdd(connectorId: $connectorId, friendlyName: $friendlyName) {
@@ -107,8 +110,8 @@ def wait_for_work_to_finish(self, work_id: str):
107110
status = state["status"]
108111

109112
if state["errors"]:
110-
self.api.log(
111-
"error", f"Unexpected connector error {state['errors']}"
113+
self.api.app_logger.error(
114+
"Unexpected connector error", {"state_errors": state["errors"]}
112115
)
113116
return ""
114117

pycti/connector/__init__.py

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

0 commit comments

Comments
 (0)