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