Created
July 4, 2014 17:07
-
-
Save irmen/c3d07118a8e1a00367f5 to your computer and use it in GitHub Desktop.
Auditing import hook to see who is importing what and when
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
this code prints something like this: | |
Hello I'm about to import a module. | |
2014-07-04 19:01:12,321 [irmen@Neptune] importing /cgi | |
2014-07-04 19:01:12,323 [irmen@Neptune] importing /urlparse | |
2014-07-04 19:01:12,328 [irmen@Neptune] importing /mimetools | |
[... and some more modules...] | |
Bye. | |
""" | |
import sys | |
import logging | |
import socket | |
import os | |
import getpass | |
def setup_import_logging(): | |
class ContextFilter(logging.Filter): | |
def filter(self, record): | |
record.hostname = socket.gethostname() | |
if sys.version_info < (3, 0): | |
record.username = getpass.getuser() | |
else: | |
record.username = os.getlogin() | |
return True | |
# configure the logger, adapt as desired: | |
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s [%(username)s@%(hostname)s] %(message)s") | |
class AuditingImporter(object): | |
log = logging.getLogger("auditingimporter") | |
log.setLevel(logging.DEBUG) | |
log.addFilter(ContextFilter()) | |
def find_module(self, fullname, path): | |
return self.find_spec(fullname, path) | |
def find_spec(self, fullname, path, target=None): | |
self.log.debug("importing {path}/{fullname}".format(path=path or "", fullname=fullname)) | |
return None | |
sys.meta_path.insert(0, AuditingImporter()) | |
setup_import_logging() | |
print("Hello I'm about to import a module.") | |
import cgi # will generate a load of logging entries | |
print("Bye.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment