• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2#
3# Copyright 2016 - The Android Open Source Project
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
17import inspect
18import os
19
20
21class TraceLogger(object):
22    def __init__(self, logger):
23        self._logger = logger
24
25    @staticmethod
26    def _get_trace_info(level=1, offset=2):
27        # We want the stack frame above this and above the error/warning/info
28        inspect_stack = inspect.stack()
29        trace_info = ''
30        for i in range(level):
31            try:
32                stack_frames = inspect_stack[offset + i]
33                info = inspect.getframeinfo(stack_frames[0])
34                trace_info = '%s[%s:%s:%s]' % (trace_info,
35                                               os.path.basename(info.filename),
36                                               info.function, info.lineno)
37            except IndexError:
38                break
39        return trace_info
40
41    def _log_with(self, logging_lambda, trace_level, msg, *args, **kwargs):
42        trace_info = TraceLogger._get_trace_info(level=trace_level, offset=3)
43        logging_lambda('%s %s' % (msg, trace_info), *args, **kwargs)
44
45    def exception(self, msg, *args, **kwargs):
46        self._log_with(self._logger.exception, 5, msg, *args, **kwargs)
47
48    def debug(self, msg, *args, **kwargs):
49        self._log_with(self._logger.debug, 3, msg, *args, **kwargs)
50
51    def error(self, msg, *args, **kwargs):
52        self._log_with(self._logger.error, 3, msg, *args, **kwargs)
53
54    def warn(self, msg, *args, **kwargs):
55        self._log_with(self._logger.warn, 3, msg, *args, **kwargs)
56
57    def warning(self, msg, *args, **kwargs):
58        self._log_with(self._logger.warning, 3, msg, *args, **kwargs)
59
60    def info(self, msg, *args, **kwargs):
61        self._log_with(self._logger.info, 1, msg, *args, **kwargs)
62
63    def __getattr__(self, name):
64        return getattr(self._logger, name)
65