]> arthur.barton.de Git - netdata.git/blob - python.d/python_modules/msg.py
203751afdb051d39ab98c5f5b883c3dc772d017f
[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 = 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         timestamp = strftime('%Y-%m-%d %X')
28         msg = "%s: %s %s: %s" % (timestamp, PROGRAM, str(msg_type), " ".join(args))
29         WRITE(msg + "\n")
30         FLUSH()
31
32     global NEXT_CHECK
33     if NEXT_CHECK <= now:
34         NEXT_CHECK = now - (now % LOG_INTERVAL) + LOG_INTERVAL
35         if LOG_COUNTER < 0:
36             timestamp = strftime('%Y-%m-%d %X')
37             msg = "%s: Prevented %s log messages from displaying" % (timestamp, str(0 - LOG_COUNTER))
38             WRITE(msg + "\n")
39             FLUSH()
40
41
42 def debug(*args):
43     """
44     Print debug message on stderr.
45     """
46     if not DEBUG_FLAG:
47         return
48
49     log_msg("DEBUG", *args)
50
51
52 def error(*args):
53     """
54     Print message on stderr.
55     """
56     log_msg("ERROR", *args)
57
58
59 def info(*args):
60     """
61     Print message on stderr.
62     """
63     log_msg("INFO", *args)
64
65
66 def fatal(*args):
67     """
68     Print message on stderr and exit.
69     """
70     log_msg("FATAL", *args)
71     # using sys.stdout causes IOError: Broken Pipe
72     print('DISABLE')
73     # sys.stdout.write('DISABLE\n')
74     sys.exit(1)