1 # Copyright 2017 Cisco Systems, Inc. All rights reserved.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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
15 from datetime import datetime
16 from fluent import sender
19 class FluentLogHandler(logging.Handler):
20 '''This is a minimalist log handler for use with Fluentd
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)
26 - the runlogdate (to tie multiple run-related logs together)
27 The timestamp is retrieved by the fluentd library.
29 def __init__(self, tag, fluentd_ip='127.0.0.1', fluentd_port=24224):
30 logging.Handler.__init__(self)
32 self.formatter = logging.Formatter('%(message)s')
33 self.sender = sender.FluentSender(self.tag, port=fluentd_port)
36 def start_new_run(self):
37 '''Delimitate a new run in the stream of records with a new timestamp
39 self.runlogdate = str(datetime.now())
41 def emit(self, record):
43 "runlogdate": self.runlogdate,
44 "loglevel": record.levelname,
45 "message": self.formatter.format(record)
47 self.sender.emit(None, data)