16ff33e31c25ef20955a1d23fe8a433f8facb000
[nfvbench.git] / nfvbench / fluentd.py
1 # Copyright 2017 Cisco Systems, Inc.  All rights reserved.
2 #
3 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
4 #    not use this file except in compliance with the License. You may obtain
5 #    a copy of the License at
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
9 #    Unless required by applicable law or agreed to in writing, software
10 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 #    License for the specific language governing permissions and limitations
13 #    under the License.
14
15 import logging
16
17 from datetime import datetime
18 from fluent import sender
19 import pytz
20
21
22 class FluentLogHandler(logging.Handler):
23     '''This is a minimalist log handler for use with Fluentd
24
25     Needs to be attached to a logger using the addHandler method.
26     It only picks up from every record:
27     - the formatted message (no timestamp and no level)
28     - the level name
29     - the runlogdate (to tie multiple run-related logs together)
30     The timestamp is retrieved by the fluentd library.
31     '''
32
33     def __init__(self, tag, fluentd_ip='127.0.0.1', fluentd_port=24224):
34         logging.Handler.__init__(self)
35         self.tag = tag
36         self.formatter = logging.Formatter('%(message)s')
37         self.sender = sender.FluentSender(self.tag, host=fluentd_ip, port=fluentd_port)
38         self.runlogdate = 0
39         self.__warning_counter = 0
40         self.__error_counter = 0
41
42     def start_new_run(self):
43         '''Delimitate a new run in the stream of records with a new timestamp
44         '''
45         self.runlogdate = self.__get_timestamp()
46         # reset counters
47         self.__warning_counter = 0
48         self.__error_counter = 0
49         # send start record
50         self.__send_start_record()
51
52     def emit(self, record):
53         data = {
54             "loglevel": record.levelname,
55             "message": self.formatter.format(record),
56             "@timestamp": self.__get_timestamp()
57         }
58         # if runlogdate is 0, it's a log from server (not an nfvbench run) so do not send runlogdate
59         if self.runlogdate != 0:
60             data["runlogdate"] = self.runlogdate
61
62         self.__update_stats(record.levelno)
63         self.sender.emit(None, data)
64
65     # this function is called by summarizer
66     def record_send(self, record):
67         self.sender.emit(None, record)
68
69     # send START record for each run
70     def __send_start_record(self):
71         data = {
72             "runlogdate": self.runlogdate,
73             "loglevel": "START",
74             "message": "NFVBENCH run is started",
75             "numloglevel": 0,
76             "numerrors": 0,
77             "numwarnings": 0,
78             "@timestamp": self.__get_timestamp()
79         }
80         self.sender.emit(None, data)
81
82     # send stats related to the current run and reset state for a new run
83     def send_run_summary(self, run_summary_required):
84         if run_summary_required or self.__get_highest_level() == logging.ERROR:
85             data = {
86                 "loglevel": "RUN_SUMMARY",
87                 "message": self.__get_highest_level_desc(),
88                 "numloglevel": self.__get_highest_level(),
89                 "numerrors": self.__error_counter,
90                 "numwarnings": self.__warning_counter,
91                 "@timestamp": self.__get_timestamp()
92             }
93             # if runlogdate is 0, it's a log from server (not an nfvbench run)
94             # so don't send runlogdate
95             if self.runlogdate != 0:
96                 data["runlogdate"] = self.runlogdate
97             self.sender.emit(None, data)
98
99     def __get_highest_level(self):
100         if self.__error_counter > 0:
101             return logging.ERROR
102         elif self.__warning_counter > 0:
103             return logging.WARNING
104         return logging.INFO
105
106     def __get_highest_level_desc(self):
107         highest_level = self.__get_highest_level()
108         if highest_level == logging.INFO:
109             return "GOOD RUN"
110         elif highest_level == logging.WARNING:
111             return "RUN WITH WARNINGS"
112         return "RUN WITH ERRORS"
113
114     def __update_stats(self, levelno):
115         if levelno == logging.WARNING:
116             self.__warning_counter += 1
117         elif levelno == logging.ERROR:
118             self.__error_counter += 1
119
120     def __get_timestamp(self):
121         return datetime.utcnow().replace(tzinfo=pytz.utc).strftime(
122             "%Y-%m-%dT%H:%M:%S.%f%z")