summaryrefslogtreecommitdiff
path: root/openstackclient/common/context.py
blob: 4c04e661ff604068888d7291211ac88230015494 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#   Licensed under the Apache License, Version 2.0 (the "License"); you may
#   not use this file except in compliance with the License. You may obtain
#   a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#   WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#   License for the specific language governing permissions and limitations
#   under the License.
#

"""Context and Formatter"""

import logging
import warnings

_LOG_MESSAGE_FORMAT = ('%(asctime)s.%(msecs)03d %(process)d '
                       '%(levelname)s %(name)s [%(clouds_name)s '
                       '%(username)s %(project_name)s] %(message)s')
_LOG_DATE_FORMAT = '%Y-%m-%d %H:%M:%S'


def log_level_from_options(options):
    # if --debug, --quiet or --verbose is not specified,
    # the default logging level is warning
    log_level = logging.WARNING
    if options.verbose_level == 0:
        # --quiet
        log_level = logging.ERROR
    elif options.verbose_level == 2:
        # One --verbose
        log_level = logging.INFO
    elif options.verbose_level >= 3:
        # Two or more --verbose
        log_level = logging.DEBUG
    return log_level


def log_level_from_config(config):
    # Check the command line option
    verbose_level = config.get('verbose_level')
    if config.get('debug', False):
        verbose_level = 3
    if verbose_level == 0:
        verbose_level = 'error'
    elif verbose_level == 1:
        # If a command line option has not been specified, check the
        # configuration file
        verbose_level = config.get('log_level', 'warning')
    elif verbose_level == 2:
        verbose_level = 'info'
    else:
        verbose_level = 'debug'

    log_level = {
        'critical': logging.CRITICAL,
        'error': logging.ERROR,
        'warning': logging.WARNING,
        'info': logging.INFO,
        'debug': logging.DEBUG,
    }.get(verbose_level, logging.WARNING)
    return log_level


def set_warning_filter(log_level):
    if log_level == logging.ERROR:
        warnings.simplefilter("ignore")
    elif log_level == logging.WARNING:
        warnings.simplefilter("ignore")
    elif log_level == logging.INFO:
        warnings.simplefilter("once")


def setup_handler_logging_level(handler_type, level):
    """Setup of the handler for set the logging level

        :param handler_type: type of logging handler
        :param level: logging level
        :return: None
    """
    # Set the handler logging level of FileHandler(--log-file)
    # and StreamHandler
    for h in logging.getLogger('').handlers:
        if type(h) is handler_type:
            h.setLevel(level)


def setup_logging(shell, cloud_config):
    """Get one cloud configuration from configuration file and setup logging

        :param shell: instance of openstackclient shell
        :param cloud_config:
            instance of the cloud specified by --os-cloud
            in the configuration file
        :return: None
    """

    log_level = log_level_from_config(cloud_config.config)
    set_warning_filter(log_level)

    log_file = cloud_config.config.get('log_file', None)
    if log_file:
        # setup the logging context
        log_cont = _LogContext(
            clouds_name=cloud_config.config.get('cloud'),
            project_name=cloud_config.auth.get('project_name'),
            username=cloud_config.auth.get('username'),
        )
        # setup the logging handler
        log_handler = _setup_handler_for_logging(
            logging.FileHandler,
            log_level,
            file_name=log_file,
            context=log_cont,
        )
        if log_level == logging.DEBUG:
            # DEBUG only.
            # setup the operation_log
            shell.enable_operation_logging = True
            shell.operation_log.setLevel(logging.DEBUG)
            shell.operation_log.addHandler(log_handler)


def _setup_handler_for_logging(handler_type, level, file_name, context):
    """Setup of the handler

       Setup of the handler for addition of the logging handler,
       changes of the logging format, change of the logging level,

        :param handler_type: type of logging handler
        :param level: logging level
        :param file_name: name of log-file
        :param context: instance of _LogContext()
        :return: logging handler
    """

    root_logger = logging.getLogger('')
    handler = None
    # Setup handler for FileHandler(--os-cloud)
    handler = logging.FileHandler(
        filename=file_name,
    )
    formatter = _LogContextFormatter(
        context=context,
        fmt=_LOG_MESSAGE_FORMAT,
        datefmt=_LOG_DATE_FORMAT,
    )
    handler.setFormatter(formatter)
    handler.setLevel(level)

    # If both `--log-file` and `--os-cloud` are specified,
    # the log is output to each file.
    root_logger.addHandler(handler)

    return handler


class _LogContext(object):
    """Helper class to represent useful information about a logging context"""

    def __init__(self, clouds_name=None, project_name=None, username=None):
        """Initialize _LogContext instance

            :param clouds_name: one of the cloud name in configuration file
            :param project_name: the project name in cloud(clouds_name)
            :param username: the user name in cloud(clouds_name)
        """

        self.clouds_name = clouds_name
        self.project_name = project_name
        self.username = username

    def to_dict(self):
        return {
            'clouds_name': self.clouds_name,
            'project_name': self.project_name,
            'username': self.username
        }


class _LogContextFormatter(logging.Formatter):
    """Customize the logging format for logging handler"""

    def __init__(self, *args, **kwargs):
        self.context = kwargs.pop('context', None)
        logging.Formatter.__init__(self, *args, **kwargs)

    def format(self, record):
        d = self.context.to_dict()
        for k, v in d.items():
            setattr(record, k, v)
        return logging.Formatter.format(self, record)