blob: b59647a45c106e08f9462d9c52bc9fbff6ef05b0 [file] [log] [blame]
Tommy Carpenter81b9ed72017-08-23 11:21:44 -04001# org.onap.dcae
2# ================================================================================
3# Copyright (c) 2017 AT&T Intellectual Property. All rights reserved.
4# ================================================================================
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16# ============LICENSE_END=========================================================
17#
18# ECOMP is a trademark and service mark of AT&T Intellectual Property.
19
20import collections
21import logging, sys
22import six
23
24#####
25# Module contains utility methods
26#####
27
28def update_json(src, key, value):
29 """Updates a nested JSON value
30
31 This method does a recursive lookup for a value given a compound key and then
32 replaces that value with the passed in new value.
33
34 For example, given a src json { "a": [ { "aa": 1 }, "foo" ], "b": "2 } and a
35 key ("a", 0, "aa"), the value parameter would replace 1.
36
37 :param src: json to update
38 :type src: dict or list
39 :param key: compound key used to lookup
40 :type key: tuple
41 :param value: new value used to replace
42 :type value: object
43
44 :return: updated json
45 """
46 if key:
47 src[key[0]] = update_json(src[key[0]], key[1:], value)
48 else:
49 # We've found the value we want to replace regardless of whether or not
50 # the object we are replacing is another copmlicated data structure.
51 src = value
52 return src
53
54def _has_handlers(logger):
55 """Check if logger has handlers"""
56 if six.PY3:
57 return logger.hasHandlers()
58 else:
59 # TODO: Not sure how to check if a handler has already been attached
60 # WATCH: Downside is lines get printed multiple times
61 return False
62
63def get_logger(name, level=logging.INFO):
64 """Get a logger with sensible defaults
65
66 This method returns a logger from logging by name that has been set with sensible
67 defaults if the logger hasn't already been setup with any handlers. The
68 default handler is a stream handler to stdout.
69 """
70 logger = logging.getLogger(name)
71
72 if not _has_handlers(logger):
73 # No handlers attached which means logging hasn't been setup. Set
74 # "sensible" defaults which means stdout, INFO
75 logger.setLevel(level)
76 logger.addHandler(logging.StreamHandler(stream=sys.stdout))
77
78 return logger