]> arthur.barton.de Git - netdata.git/blob - python.d/python_modules/msg.py
freeradius_plugin: python 2.6 compatibility fix2
[netdata.git] / python.d / python_modules / msg.py
1 # -*- coding: utf-8 -*-
2 # Description: logging for netdata python.d modules
3
4 import traceback
5 import sys
6 from time import time, strftime
7
8 DEBUG_FLAG = False
9 TRACE_FLAG = False
10 PROGRAM = ""
11 LOG_COUNTER = 0
12 LOG_THROTTLE = 10000 # has to be too big during init
13 LOG_INTERVAL = 1     # has to be too low during init
14 LOG_NEXT_CHECK = 0
15
16 WRITE = sys.stderr.write
17 FLUSH = sys.stderr.flush
18
19
20 def log_msg(msg_type, *args):
21     """
22     Print message on stderr.
23     :param msg_type: str
24     """
25     global LOG_COUNTER
26     global LOG_THROTTLE
27     global LOG_INTERVAL
28     global LOG_NEXT_CHECK
29     now = time()
30
31     if not DEBUG_FLAG:
32         LOG_COUNTER += 1
33
34     # WRITE("COUNTER " + str(LOG_COUNTER) + " THROTTLE " + str(LOG_THROTTLE) + " INTERVAL " + str(LOG_INTERVAL) + " NOW " + str(now) + " NEXT " + str(LOG_NEXT_CHECK) + "\n")
35
36     if LOG_COUNTER <= LOG_THROTTLE or msg_type == "FATAL" or msg_type == "ALERT":
37         timestamp = strftime('%Y-%m-%d %X')
38         msg = "%s: %s %s: %s" % (timestamp, PROGRAM, str(msg_type), " ".join(args))
39         WRITE(msg + "\n")
40         FLUSH()
41     elif LOG_COUNTER == LOG_THROTTLE + 1:
42         timestamp = strftime('%Y-%m-%d %X')
43         msg = "%s: python.d.plugin: throttling further log messages for %s seconds" % (timestamp, str(int(LOG_NEXT_CHECK + 0.5) - int(now)))
44         WRITE(msg + "\n")
45         FLUSH()
46
47     if LOG_NEXT_CHECK <= now:
48         if LOG_COUNTER >= LOG_THROTTLE:
49             timestamp = strftime('%Y-%m-%d %X')
50             msg = "%s: python.d.plugin: Prevented %s log messages from displaying" % (timestamp, str(LOG_COUNTER - LOG_THROTTLE))
51             WRITE(msg + "\n")
52             FLUSH()
53         LOG_NEXT_CHECK = now - (now % LOG_INTERVAL) + LOG_INTERVAL
54         LOG_COUNTER = 0
55
56     if TRACE_FLAG:
57         if msg_type == "FATAL" or msg_type == "ERROR" or msg_type == "ALERT":
58             traceback.print_exc()
59
60
61 def debug(*args):
62     """
63     Print debug message on stderr.
64     """
65     if not DEBUG_FLAG:
66         return
67
68     log_msg("DEBUG", *args)
69
70
71 def error(*args):
72     """
73     Print message on stderr.
74     """
75     log_msg("ERROR", *args)
76
77
78 def alert(*args):
79     """
80     Print message on stderr.
81     """
82     log_msg("ALERT", *args)
83
84
85 def info(*args):
86     """
87     Print message on stderr.
88     """
89     log_msg("INFO", *args)
90
91
92 def fatal(*args):
93     """
94     Print message on stderr and exit.
95     """
96     try:
97         log_msg("FATAL", *args)
98         print('DISABLE')
99     except:
100         pass
101     sys.exit(1)