1## This file is part of Scapy
2## See http://www.secdev.org/projects/scapy for more informations
3## Copyright (C) Philippe Biondi <phil@secdev.org>
4## This program is published under a GPLv2 license
5
6"""
7Logging subsystem and basic exception class.
8"""
9
10#############################
11##### Logging subsystem #####
12#############################
13
14class Scapy_Exception(Exception):
15    pass
16
17import logging,traceback,time
18
19class ScapyFreqFilter(logging.Filter):
20    def __init__(self):
21        logging.Filter.__init__(self)
22        self.warning_table = {}
23    def filter(self, record):
24        from .config import conf
25        wt = conf.warning_threshold
26        if wt > 0:
27            stk = traceback.extract_stack()
28            caller=None
29            for f,l,n,c in stk:
30                if n == 'warning':
31                    break
32                caller = l
33            tm,nb = self.warning_table.get(caller, (0,0))
34            ltm = time.time()
35            if ltm-tm > wt:
36                tm = ltm
37                nb = 0
38            else:
39                if nb < 2:
40                    nb += 1
41                    if nb == 2:
42                        record.msg = "more "+record.msg
43                else:
44                    return 0
45            self.warning_table[caller] = (tm,nb)
46        return 1
47
48log_scapy = logging.getLogger("scapy")
49console_handler = logging.StreamHandler()
50console_handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
51log_scapy.addHandler(console_handler)
52log_runtime = logging.getLogger("scapy.runtime")          # logs at runtime
53log_runtime.addFilter(ScapyFreqFilter())
54log_interactive = logging.getLogger("scapy.interactive")  # logs in interactive functions
55log_loading = logging.getLogger("scapy.loading")          # logs when loading scapy
56
57
58def warning(x):
59    log_runtime.warning(x)
60
61