]> arthur.barton.de Git - netdata.git/blob - python.d/python_modules/msg.py
add log flood prevention
[netdata.git] / python.d / python_modules / msg.py
1 # -*- coding: utf-8 -*-
2 # Description: logging for netdata python.d modules
3
4 import sys
5 from time import time
6
7 DEBUG_FLAG = False
8 PROGRAM = ""
9 LOG_COUNTER = 2
10 LOG_INTERVAL = 5
11 NEXT_CHECK = 0
12
13 WRITE = sys.stderr.write
14 FLUSH = sys.stderr.flush
15
16
17 def log_msg(msg_type, *args):
18     """
19     Print message on stderr.
20     :param msg_type: str
21     """
22     global LOG_COUNTER
23     if not DEBUG_FLAG:
24         LOG_COUNTER -= 1
25     now = time()
26     if LOG_COUNTER >= 0:
27         msg = "%s %s: %s" % (PROGRAM, str(msg_type), " ".join(args))
28         WRITE(msg + "\n")
29         FLUSH()
30
31     global NEXT_CHECK
32     if NEXT_CHECK <= now:
33         NEXT_CHECK = now - (now % LOG_INTERVAL) + LOG_INTERVAL
34         if LOG_COUNTER < 0:
35             msg = "Prevented %s log messages from displaying" % str(0 - LOG_COUNTER)
36             WRITE(msg + "\n")
37             FLUSH()
38
39
40 def debug(*args):
41     """
42     Print debug message on stderr.
43     """
44     if not DEBUG_FLAG:
45         return
46
47     log_msg("DEBUG", *args)
48
49
50 def error(*args):
51     """
52     Print message on stderr.
53     """
54     log_msg("ERROR", *args)
55
56
57 def info(*args):
58     """
59     Print message on stderr.
60     """
61     log_msg("INFO", *args)
62
63
64 def fatal(*args):
65     """
66     Print message on stderr and exit.
67     """
68     log_msg("FATAL", *args)
69     # using sys.stdout causes IOError: Broken Pipe
70     print('DISABLE')
71     # sys.stdout.write('DISABLE\n')
72     sys.exit(1)