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