683d4ce9d26074ec924ab47ae519f9f19331e002
[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 from datetime import datetime
16 from fluent import sender
17 import logging
18
19 class FluentLogHandler(logging.Handler):
20     '''This is a minimalist log handler for use with Fluentd
21
22     Needs to be attached to a logger using the addHandler method.
23     It only picks up from every record:
24     - the formatted message (no timestamp and no level)
25     - the level name
26     - the runlogdate (to tie multiple run-related logs together)
27     The timestamp is retrieved by the fluentd library.
28     '''
29     def __init__(self, tag, fluentd_ip='127.0.0.1', fluentd_port=24224):
30         logging.Handler.__init__(self)
31         self.tag = tag
32         self.formatter = logging.Formatter('%(message)s')
33         self.sender = sender.FluentSender(self.tag, port=fluentd_port)
34         self.start_new_run()
35
36     def start_new_run(self):
37         '''Delimitate a new run in the stream of records with a new timestamp
38         '''
39         self.runlogdate = str(datetime.now())
40
41     def emit(self, record):
42         data = {
43             "runlogdate": self.runlogdate,
44             "loglevel": record.levelname,
45             "message": self.formatter.format(record)
46         }
47         self.sender.emit(None, data)