lib.cuckoo.core.log

Package lib :: Package cuckoo :: Package core :: Module log |
[hide private]
[frames] | no frames]

# Source Code for Module lib.cuckoo.core.log

     1  # Copyright (C) 2016 Cuckoo Foundation.
     2  # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
     3  # See the file 'docs/LICENSE' for copying permission.
     4
     5  import copy
     6  import logging.handlers
     7  import os.path
     8  import thread
     9
    10  from lib.cuckoo.common.colors import red, yellow, cyan
    11  from lib.cuckoo.core.database import Database
    12  from lib.cuckoo.common.constants import CUCKOO_ROOT
    13
    14  _tasks = {}
    15
    16 -class DatabaseHandler(logging.Handler):
    17      """Logging to database handler.
    18      Used to log errors related to tasks in database.
    19      """
    20
    21 -    def emit(self, record):
    22          if hasattr(record, "task_id"):
    23              db = Database()
    24              db.add_error(self.format(record), int(record.task_id))
    25
    26 -class TaskHandler(logging.Handler):
    27      """Per-task logger.
    28      Used to log all task specific events to a per-task cuckoo.log log file.
    29      """
    30
    31 -    def emit(self, record):
    32          task_id = _tasks.get(thread.get_ident())
    33          if not task_id:
    34              return
    35
    36          # Don't bother, this will be improved with #863 anyway.
    37          logpath = os.path.join(
    38              CUCKOO_ROOT, "storage", "analyses", "%s" % task_id, "cuckoo.log"
    39          )
    40
    41          with open(logpath, "a+b") as f:
    42              f.write("%s\n" % self.format(record))
    43
    44 -class ConsoleHandler(logging.StreamHandler):
    45      """Logging to console handler."""
    46
    47 -    def emit(self, record):
    48          colored = copy.copy(record)
    49
    50          if record.levelname == "WARNING":
    51              colored.msg = yellow(record.msg)
    52          elif record.levelname == "ERROR" or record.levelname == "CRITICAL":
    53              colored.msg = red(record.msg)
    54          else:
    55              if "analysis procedure completed" in record.msg:
    56                  colored.msg = cyan(record.msg)
    57              else:
    58                  colored.msg = record.msg
    59
    60          logging.StreamHandler.emit(self, colored)
    61
    62 -def task_log_start(task_id):
    63      """Associate a thread with a task."""
    64      _tasks[thread.get_ident()] = task_id
    65
    66 -def task_log_stop(task_id):
    67      """Disassociate a thread from a task."""
    68      _tasks.pop(thread.get_ident(), None)
    69