1 # Copyright (C) 2014 Nippon Telegraph and Telephone Corporation.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain 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,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
17 Module for stats related classes and utilities.
24 from ryu.services.protocols.bgp.rtconf.base import ConfWithId
27 _STATS_LOGGER = logging.getLogger('stats')
29 # Various stats related constants.
30 DEFAULT_LOG_LEVEL = logging.INFO
32 RESOURCE_ID = 'resource_id'
33 RESOURCE_NAME = 'resource_name'
34 TIMESTAMP = 'timestamp'
35 LOG_LEVEL = 'log_level'
37 STATS_RESOURCE = 'stats_resource'
38 STATS_SOURCE = 'stats_source'
40 # VRF related stat constants
41 REMOTE_ROUTES = 'remote_routes'
42 LOCAL_ROUTES = 'local_routes'
44 # Peer related stat constant.
45 UPDATE_MSG_IN = 'update_message_in'
46 UPDATE_MSG_OUT = 'update_message_out'
47 TOTAL_MSG_IN = 'total_message_in'
48 TOTAL_MSG_OUT = 'total_message_out'
49 FMS_EST_TRANS = 'fsm_established_transitions'
53 def log(stats_resource=None, stats_source=None, log_level=DEFAULT_LOG_LEVEL,
55 """Utility to log given stats to *stats* logger.
57 Stats to log are given by `stats_source` and in its absence we log
58 `kwargs`. *stats* logger is configured independently from any logger.
59 Only stats should be logged to this logger. Will add current timestamp
60 to the logged stats if not given.
63 - `stats_resource`: any object that complies with `id` and `name`
65 - `stats_source`: any callable that give a `dict` that will be
66 logged to *stats* logger.
67 - `log_level`: str representing level at which to log this stats
69 - `**kwargs`: if `stats_source` is not given, we log this `dict`.
72 # Get stats from source if given.
73 if stats_source is not None:
74 kwargs = stats_source()
76 if stats_resource is None:
77 if RESOURCE_ID not in kwargs or RESOURCE_NAME not in kwargs:
78 raise ValueError('Missing required stats labels.')
80 if not (hasattr(stats_resource, ConfWithId.ID) and
81 hasattr(stats_resource, ConfWithId.NAME)):
82 raise ValueError('Given stats source is missing id or name'
84 kwargs[RESOURCE_ID] = stats_resource.id
85 kwargs[RESOURCE_NAME] = stats_resource.name
87 if TIMESTAMP not in kwargs:
88 kwargs[TIMESTAMP] = datetime.datetime.utcfromtimestamp(
89 time.time()).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
91 _STATS_LOGGER.log(log_level,
96 log(log_level=logging.DEBUG, **kwargs)
100 log(log_level=logging.INFO, **kwargs)