-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathxlog.py
More file actions
63 lines (51 loc) · 2.03 KB
/
xlog.py
File metadata and controls
63 lines (51 loc) · 2.03 KB
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
# xlog.py
import logging
# Adding the 'username' and 'funcname' specifiers
# They must be attributes of the log record
class OurLogRecord(logging.LogRecord):
def __init__(self, name, level, fn, lno, msg, args, exc_info, func):
# Don't pass all args to LogRecord constructor bc it doesn't expect "extra"
logging.LogRecord.__init__(self, name, level, fn, lno, msg, args, exc_info, func)
# Adding format specifiers is as simple as adding attributes with
# same name to the log record object:
self.funcname = calling_func_name()
self.username = current_user()
class OurLogger(logging.getLoggerClass()):
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None):
# Don't pass all makeRecord args to OurLogRecord bc it doesn't expect "extra"
rv = OurLogRecord(name, level, fn, lno, msg, args, exc_info, func)
# Handle the new extra parameter.
# This if block was copied from Logger.makeRecord
if extra:
for key in extra:
if (key in ["message", "asctime"]) or (key in rv.__dict__):
raise KeyError("Attempt to overwrite %r in LogRecord" % key)
rv.__dict__[key] = extra[key]
return rv
# Register our logger
# logging.setLoggerClass(OurLogger)
# Current user
def current_user():
import pwd, os
try:
return pwd.getpwuid(os.getuid()).pw_name
except KeyError:
return "(unknown)"
# Calling Function Name
def calling_func_name():
return calling_frame().f_code.co_name
import os, sys
def calling_frame():
f = sys._getframe()
while True:
if is_user_source_file(f.f_code.co_filename):
return f
f = f.f_back
def is_user_source_file(filename):
return os.path.normcase(filename) not in (_srcfile, logging._srcfile)
def _current_source_file():
if __file__[-4:].lower() in ['.pyc', '.pyo']:
return __file__[:-4] + '.py'
else:
return __file__
_srcfile = os.path.normcase(_current_source_file())