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
|
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Red Hat, Inc. <http://www.redhat.com>
# This file is part of GlusterFS.
#
# This file is licensed to you under your choice of the GNU Lesser
# General Public License, version 3 or any later version (LGPLv3 or
# later), or the GNU General Public License, version 2 (GPLv2), in all
# cases as published by the Free Software Foundation.
#
import logging
from logging import Logger, handlers
import sys
import time
class GLogger(Logger):
"""Logger customizations for gsyncd.
It implements a log format similar to that of glusterfs.
"""
def makeRecord(self, name, level, *a):
rv = Logger.makeRecord(self, name, level, *a)
rv.nsecs = (rv.created - int(rv.created)) * 1000000
fr = sys._getframe(4)
callee = fr.f_locals.get('self')
if callee:
ctx = str(type(callee)).split("'")[1].split('.')[-1]
else:
ctx = '<top>'
if not hasattr(rv, 'funcName'):
rv.funcName = fr.f_code.co_name
rv.lvlnam = logging.getLevelName(level)[0]
rv.ctx = ctx
return rv
LOGFMT = ("[%(asctime)s.%(nsecs)d] %(lvlnam)s [%(module)s{0}"
":%(lineno)s:%(funcName)s] %(ctx)s: %(message)s")
def setup_logging(level="INFO", label="", log_file=""):
if label:
label = "(" + label + ")"
filename = None
stream = None
if log_file:
if log_file in ('-', '/dev/stderr'):
stream = sys.stderr
elif log_file == '/dev/stdout':
stream = sys.stdout
else:
filename = log_file
datefmt = "%Y-%m-%d %H:%M:%S"
fmt = LOGFMT.format(label)
logging.root = GLogger("root", level)
logging.setLoggerClass(GLogger)
logging.Formatter.converter = time.gmtime # Log in GMT/UTC time
logging.getLogger().handlers = []
logging.getLogger().setLevel(level)
if filename is not None:
logging_handler = handlers.WatchedFileHandler(filename)
formatter = logging.Formatter(fmt=fmt,
datefmt=datefmt)
logging_handler.setFormatter(formatter)
logging.getLogger().addHandler(logging_handler)
else:
logging.basicConfig(stream=stream,
format=fmt,
datefmt=datefmt,
level=level)
|