File: proxy_logger.py

package info (click to toggle)
python-ruffus 2.6.3%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 20,828 kB
  • ctags: 2,843
  • sloc: python: 15,745; makefile: 180; sh: 14
file content (354 lines) | stat: -rw-r--r-- 11,622 bytes parent folder | download | duplicates (2)
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
#!/usr/bin/env python
################################################################################
#
#   proxy_logger.py
#
#
#   Copyright (c) 10/9/2009 Leo Goodstadt
#
#   Permission is hereby granted, free of charge, to any person obtaining a copy
#   of this software and associated documentation files (the "Software"), to deal
#   in the Software without restriction, including without limitation the rights
#   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#   copies of the Software, and to permit persons to whom the Software is
#   furnished to do so, subject to the following conditions:
#
#   The above copyright notice and this permission notice shall be included in
#   all copies or substantial portions of the Software.
#
#   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#   THE SOFTWARE.
#################################################################################
"""
****************************************************************************
Create proxy for logging for use with multiprocessing
****************************************************************************

These can be safely sent (marshalled) across process boundaries


===========
Example 1
===========

    Set up logger from config file::

        from proxy_logger import *
        args={}
        args["config_file"] = "/my/config/file"

        (logger_proxy,
         logging_mutex) = make_shared_logger_and_proxy (setup_std_shared_logger,
                                                        "my_logger", args)


===========
Example 2
===========

    Log to file ``"/my/lg.log"`` in the specified format (Time / Log name / Event type / Message).

    Delay file creation until first log.

    Only log ``Debug`` messages

        Other alternatives for the logging threshold (``args["level"]``) include

            * ``logging.DEBUG``
            * ``logging.INFO``
            * ``logging.WARNING``
            * ``logging.ERROR``
            * ``logging.CRITICAL``

    ::

        from proxy_logger import *
        args={}
        args["file_name"] = "/my/lg.log"
        args["formatter"] = "%(asctime)s - %(name)s - %(levelname)6s - %(message)s"
        args["delay"]     = True
        args["level"]     = logging.DEBUG

        (logger_proxy,
         logging_mutex) = make_shared_logger_and_proxy (setup_std_shared_logger,
                                                        "my_logger", args)

===========
Example 3
===========

    Rotate log files every 20 Kb, with up to 10 backups.
    ::

        from proxy_logger import *
        args={}
        args["file_name"] = "/my/lg.log"
        args["rotating"] = True
        args["maxBytes"]=20000
        args["backupCount"]=10
        (logger_proxy,
         logging_mutex) = make_shared_logger_and_proxy (setup_std_shared_logger,
                                                        "my_logger", args)



==============
To use:
==============

    ::

        (logger_proxy,
         logging_mutex) = make_shared_logger_and_proxy (setup_std_shared_logger,
                                                        "my_logger", args)

        with logging_mutex:
            my_log.debug('This is a debug message')
            my_log.info('This is an info message')
            my_log.warning('This is a warning message')
            my_log.error('This is an error message')
            my_log.critical('This is a critical error message')
            my_log.log(logging.DEBUG, 'This is a debug message')

    Note that the logging function ``exception()`` is not included because python
    stack trace information is not well-marshalled
    (`pickle <http://docs.python.org/library/pickle.html>`_\ d) across processes.

"""





#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   imports


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

import sys,os


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Shared logging


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

import multiprocessing
import multiprocessing.managers


import logging
import logging.handlers



#
#   setup_logger
#
def setup_std_shared_logger(logger_name, args):
    """
    This function is a simple around wrapper around the python
    `logging <http://docs.python.org/library/logging.html>`_ module.

    This *logger_factory* example creates logging objects which can
    then be managed by proxy via ``ruffus.proxy_logger.make_shared_logger_and_proxy()``

    This can be:

        * a `disk log file <http://docs.python.org/library/logging.html#filehandler>`_
        * a automatically backed-up `(rotating) log <http://docs.python.org/library/logging.html#rotatingfilehandler>`_.
        * any log specified in a `configuration file <http://docs.python.org/library/logging.html#configuration-file-format>`_

    These are specified in the ``args`` dictionary forwarded by ``make_shared_logger_and_proxy()``

    :param logger_name: name of log
    :param args: a dictionary of parameters forwarded from ``make_shared_logger_and_proxy()``

        Valid entries include:

            .. describe:: "level"

                Sets the `threshold <http://docs.python.org/library/logging.html#logging.Handler.setLevel>`_ for the logger.

            .. describe:: "config_file"

                The logging object is configured from this `configuration file <http://docs.python.org/library/logging.html#configuration-file-format>`_.

            .. describe:: "file_name"

                Sets disk log file name.

            .. describe:: "rotating"

                Chooses a `(rotating) log <http://docs.python.org/library/logging.html#rotatingfilehandler>`_.

            .. describe:: "maxBytes"

                Allows the file to rollover at a predetermined size

            .. describe:: "backupCount"

                If backupCount is non-zero, the system will save old log files by appending the extensions ``.1``, ``.2``, ``.3`` etc., to the filename.

            .. describe:: "delay"

                Defer file creation until the log is written to.

            .. describe:: "formatter"

                `Converts <http://docs.python.org/library/logging.html#formatter-objects>`_ the message to a logged entry string.
                For example,
                ::

                    "%(asctime)s - %(name)s - %(levelname)6s - %(message)s"



    """

    #
    #   Log file name with logger level
    #
    new_logger = logging.getLogger(logger_name)
    if "level" in args:
        new_logger.setLevel(args["level"])

    if "config_file" in args:
        logging.config.fileConfig(args["config_file"])

    else:
        if "file_name" not in args:
            raise Exception("Missing file name for log. Remember to set 'file_name'")
        log_file_name = args["file_name"]

        if "rotating" in args:
            rotating_args = {}
            # override default
            rotating_args["maxBytes"]=args.get("maxBytes", 100000)
            rotating_args["backupCount"]=args.get("backupCount", 5)
            handler = logging.handlers.RotatingFileHandler( log_file_name, **rotating_args)
        else:
            defer_loggin = "delay" in args
            handler = logging.handlers.RotatingFileHandler( log_file_name, delay=defer_loggin)

        #       %(name)s
        #       %(levelno)s
        #       %(levelname)s
        #       %(pathname)s
        #       %(filename)s
        #       %(module)s
        #       %(funcName)s
        #       %(lineno)d
        #       %(created)f
        #       %(relativeCreated)d
        #       %(asctime)s
        #       %(msecs)d
        #       %(thread)d
        #       %(threadName)s
        #       %(process)d
        #       %(message)s
        #
        # E.g.: "%(asctime)s - %(name)s - %(levelname)6s - %(message)s"
        #
        if "formatter" in args:
            my_formatter = logging.Formatter(args["formatter"])
            handler.setFormatter(my_formatter)

        new_logger.addHandler(handler)

    #
    #   This log object will be wrapped in proxy
    #
    return new_logger


#
#   Proxy object for logging
#       Logging messages will be marshalled (forwarded) to the process where the
#       shared log lives
#
class LoggerProxy(multiprocessing.managers.BaseProxy):
    def debug(self, *args, **kwargs):
        return self._callmethod('debug', args, kwargs)
    def log(self, *args, **kwargs):
        return self._callmethod('log', args, kwargs)
    def info(self, *args, **kwargs):
        return self._callmethod('info', args, kwargs)
    def warning(self, *args, **kwargs):
        return self._callmethod('warning', args, kwargs)
    def error(self, *args, **kwargs):
        return self._callmethod('error', args, kwargs)
    def critical(self, *args, **kwargs):
        return self._callmethod('critical', args, kwargs)
    def log(self, *args, **kwargs):
        return self._callmethod('log', args, kwargs)
    def __str__ (self):
        return "<LoggingProxy>"
    def __repr__ (self):
        return 'LoggerProxy()'

#
#   Register the setup_logger function as a proxy for setup_logger
#
#   We use SyncManager as a base class so we can get a lock proxy for synchronising
#       logging later on
#
class LoggingManager(multiprocessing.managers.SyncManager):
    """
    Logging manager sets up its own process and will create the real Log object there
    We refer to this (real) log via proxies
    """
    pass




def make_shared_logger_and_proxy (logger_factory, logger_name, args):
    """
    Make a `logging <http://docs.python.org/library/logging.html>`_ object
    called "\ ``logger_name``\ " by calling ``logger_factory``\ (``args``\ )

    This function will return a proxy to the shared logger which can be copied to jobs
    in other processes, as well as a mutex which can be used to prevent simultaneous logging
    from happening.

    :param logger_factory: functions which creates and returns an object with the
                           `logging <http://docs.python.org/library/logging.html>`_ interface.
                           ``setup_std_shared_logger()`` is one example of a logger factory.
    :param logger_name: name of log
    :param args: parameters passed (as a single argument) to ``logger_factory``
    :returns: a proxy to the shared logger which can be copied to jobs in other processes
    :returns: a mutex which can be used to prevent simultaneous logging from happening

    """
    #
    #   make shared log and proxy
    #
    manager = LoggingManager()
    manager.register(   'setup_logger',
                        logger_factory,
                        proxytype=LoggerProxy,
                        exposed = ( 'critical', 'log',
                                    'info', 'debug', 'warning', 'error'))
    manager.start()
    logger_proxy = manager.setup_logger(logger_name, args)

    #
    #   make sure we are not logging at the same time in different processes
    #
    logging_mutex = manager.Lock()

    return logger_proxy, logging_mutex