Add support for Python 3
[yardstick.git] / yardstick / dispatcher / file.py
1 # Copyright 2013 IBM Corp
2 # All Rights Reserved.
3 #
4 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
5 #    not use this file except in compliance with the License. You may obtain
6 #    a copy of the License at
7 #
8 #         http://www.apache.org/licenses/LICENSE-2.0
9 #
10 #    Unless required by applicable law or agreed to in writing, software
11 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 #    License for the specific language governing permissions and limitations
14 #    under the License.
15
16 # yardstick comment: this is a modified copy of
17 # ceilometer/ceilometer/dispatcher/file.py
18
19 from __future__ import absolute_import
20
21 import logging
22 import logging.handlers
23
24 from oslo_serialization import jsonutils
25 from oslo_config import cfg
26
27 from yardstick.dispatcher.base import Base as DispatchBase
28
29 CONF = cfg.CONF
30 OPTS = [
31     cfg.StrOpt('file_path',
32                default='/tmp/yardstick.out',
33                help='Name and the location of the file to record '
34                     'data.'),
35     cfg.IntOpt('max_bytes',
36                default=0,
37                help='The max size of the file.'),
38     cfg.IntOpt('backup_count',
39                default=0,
40                help='The max number of the files to keep.'),
41 ]
42 CONF.register_opts(OPTS, group="dispatcher_file")
43
44
45 class FileDispatcher(DispatchBase):
46     """Dispatcher class for recording data to a file.
47     """
48
49     __dispatcher_type__ = "File"
50
51     def __init__(self, conf):
52         super(FileDispatcher, self).__init__(conf)
53         self.log = None
54
55         # if the directory and path are configured, then log to the file
56         if CONF.dispatcher_file.file_path:
57             dispatcher_logger = logging.Logger('dispatcher.file')
58             dispatcher_logger.setLevel(logging.INFO)
59             # create rotating file handler which logs result
60             rfh = logging.handlers.RotatingFileHandler(
61                 self.conf.get('file_path', CONF.dispatcher_file.file_path),
62                 maxBytes=CONF.dispatcher_file.max_bytes,
63                 backupCount=CONF.dispatcher_file.backup_count,
64                 encoding='utf8')
65
66             rfh.setLevel(logging.INFO)
67             # Only wanted the data to be saved in the file, not the
68             # project root logger.
69             dispatcher_logger.propagate = False
70             dispatcher_logger.addHandler(rfh)
71             self.log = dispatcher_logger
72
73     def record_result_data(self, data):
74         if self.log:
75             self.log.info(jsonutils.dump_as_bytes(data))
76
77     def flush_result_data(self):
78         pass