~thomir-deactivatedaccount/uservice-utils/trunk-add-queue

« back to all changes in this revision

Viewing changes to uservice_utils/logging.py

  • Committer: Ubuntu CI Bot
  • Author(s): Thomi Richards
  • Date: 2015-04-02 03:04:50 UTC
  • mfrom: (5.1.2 trunk-add-logging-decorator)
  • Revision ID: ubuntu_ci_bot-20150402030450-93cncccw9wx8ykfw
Add the ExtraLogger class. [r=Celso Providelo]

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
 
18
18
"""Code to configure logging for micro-services."""
19
19
 
 
20
import collections
20
21
import logging
21
22
import logging.handlers
22
23
import os
78
79
                int(config['logstash']['version'])
79
80
            )
80
81
        )
 
82
 
 
83
 
 
84
class ExtraLogger(logging.Logger):
 
85
 
 
86
    """A logger that handles passing 'extra' arguments to all logging calls.
 
87
 
 
88
    Tired of having to write:
 
89
 
 
90
    logger.info("Some message", extra=extra)
 
91
 
 
92
    ... everywhere?
 
93
 
 
94
    Now you can install this class as the Logger class:
 
95
 
 
96
    >>> import logging
 
97
    >>> logging.setLoggerClass(ExtraLogger)
 
98
 
 
99
    Then, to use it, get your logger as usual:
 
100
 
 
101
    >>> logger = logging.getLogger(__name__)
 
102
 
 
103
    ...and set your extra arguments once only:
 
104
 
 
105
    >>> logger.set_extra_args(dict(foo='bar', baz='123'))
 
106
 
 
107
    And those arguments will be included in all normal log messages:
 
108
 
 
109
    >>> logger.info("Hello World") # message will contain extra args set above
 
110
 
 
111
    Extra arguments can be passed to individual logging calls, and will take
 
112
    priority over any set with the set_extra_args call.
 
113
 
 
114
    """
 
115
 
 
116
    def __init__(self, *args, **kwargs):
 
117
        super().__init__(*args, **kwargs)
 
118
        self._extra_args = dict()
 
119
 
 
120
    def set_extra_args(self, extra_args):
 
121
        """Set the 'extra' arguments you want to be passed to every log message.
 
122
 
 
123
        :param extra_args: A mapping type that contains the extra arguments you
 
124
            want to store.
 
125
        :raises TypeError: if extra_args is not a mapping type.
 
126
 
 
127
        """
 
128
        if not isinstance(extra_args, collections.Mapping):
 
129
            raise TypeError("extra_args must be a mapping")
 
130
        self._extra_args = extra_args
 
131
 
 
132
    def makeRecord(self, name, level, fn, lno, msg, args, exc_info,
 
133
                   func=None, user_extra=None, sinfo=None):
 
134
        extra = self._extra_args.copy()
 
135
        if user_extra:
 
136
            extra.update(user_extra)
 
137
        return super().makeRecord(name, level, fn, lno, msg, args, exc_info,
 
138
                                  func, extra, sinfo)
 
139
 
 
140