Skip to content

SpiderFoot automates OSINT for threat intelligence and mapping your attack surface.

Batch log to db (#1481)

TheTechromancer926a043b1e93
diff --git a/spiderfoot/db.py b/spiderfoot/db.py
index b42f2870..4fd3213f 100644
--- a/spiderfoot/db.py
+++ b/spiderfoot/db.py
@@ -481,6 +481,52 @@ class SpiderFootDb:
except sqlite3.Error as e:
raise IOError(f"SQL error encountered when retrieving event types: {e.args[0]}")
+ def scanLogEvents(self, batch):
+ """Logs a batch of events to the database.
+
+ Args:
+ batch (list): tuples containing: instanceId, classification, message, component, logTime
+
+ Raises:
+ TypeError: arg type was invalid
+ IOError: database I/O failed
+
+ Returns:
+ logResult: Whether the logging operation succeeded
+ """
+
+ inserts = []
+
+ for instanceId, classification, message, component, logTime in batch:
+ if not isinstance(instanceId, str):
+ raise TypeError(f"instanceId is {type(instanceId)}; expected str()")
+
+ if not isinstance(classification, str):
+ raise TypeError(f"classification is {type(classification)}; expected str()")
+
+ if not isinstance(message, str):
+ raise TypeError(f"message is {type(message)}; expected str()")
+
+ if not component:
+ component = "SpiderFoot"
+
+ inserts.append((instanceId, logTime * 1000, component, classification, message))
+
+ if inserts:
+ qry = "INSERT INTO tbl_scan_log \
+ (scan_instance_id, generated, component, type, message) \
+ VALUES (?, ?, ?, ?, ?)"
+
+ with self.dbhLock:
+ try:
+ self.dbh.executemany(qry, inserts)
+ self.conn.commit()
+ except sqlite3.Error as e:
+ if "locked" not in e.args[0] and "thread" not in e.args[0]:
+ raise IOError(f"Unable to log scan event in DB: {e.args[0]}")
+ return False
+ return True
+
def scanLogEvent(self, instanceId, classification, message, component=None):
"""Log an event to the database.
diff --git a/spiderfoot/logger.py b/spiderfoot/logger.py
index a0dd7289..9ab03a48 100644
--- a/spiderfoot/logger.py
+++ b/spiderfoot/logger.py
@@ -1,5 +1,7 @@
+import atexit
import logging
import sys
+import time
from contextlib import suppress
from logging.handlers import QueueHandler, QueueListener
@@ -21,6 +23,12 @@ class SpiderFootSqliteLogHandler(logging.Handler):
"""
self.opts = opts
self.dbh = None
+ self.batch = []
+ if self.opts.get('_debug', False):
+ self.batch_size = 100
+ else:
+ self.batch_size = 5
+ self.shutdown_hook = False
super().__init__()
def emit(self, record: 'logging.LogRecord') -> None:
@@ -29,18 +37,28 @@ class SpiderFootSqliteLogHandler(logging.Handler):
Args:
record (logging.LogRecord): Log event record
"""
- if self.dbh is None:
- # Create a new database handle when the first log record is received
- self.makeDbh()
+ if not self.shutdown_hook:
+ atexit.register(self.logBatch)
+ self.shutdown_hook = True
scanId = getattr(record, "scanId", None)
component = getattr(record, "module", None)
if scanId:
level = ("STATUS" if record.levelname == "INFO" else record.levelname)
- logResult = self.dbh.scanLogEvent(scanId, level, record.getMessage(), component=component)
- if logResult is False:
- # Try to recreate database handle if insert failed
- self.makeDbh()
- self.dbh.scanLogEvent(scanId, level, record.getMessage(), component=component)
+ self.batch.append((scanId, level, record.getMessage(), component, time.time()))
+ if len(self.batch) >= self.batch_size:
+ self.logBatch()
+
+ def logBatch(self):
+ batch = self.batch
+ self.batch = []
+ if self.dbh is None:
+ # Create a new database handle when the first log batch is processed
+ self.makeDbh()
+ logResult = self.dbh.scanLogEvents(batch)
+ if logResult is False:
+ # Try to recreate database handle if insert failed
+ self.makeDbh()
+ self.dbh.scanLogEvents(batch)
def makeDbh(self) -> None:
"""TBD."""
@@ -104,7 +122,6 @@ def logListenerSetup(loggingQueue, opts: dict = None) -> 'logging.handlers.Queue
else:
handlers = []
- import atexit
if doLogging and opts is not None:
sqlite_handler = SpiderFootSqliteLogHandler(opts)
sqlite_handler.setLevel(logLevel)