Skip to content

Instantly share code, notes, and snippets.

@tzickel
Created September 22, 2018 09:27
Show Gist options
  • Save tzickel/0abbed10de4dd18c82d7ef618e6236b5 to your computer and use it in GitHub Desktop.
Save tzickel/0abbed10de4dd18c82d7ef618e6236b5 to your computer and use it in GitHub Desktop.
If you want to insert file name, line number and function name to logging functions (this script needs redbaron installed)
import redbaron
import re
logfunctions = ['info', 'warning', 'error', 'critical', 'exception']
#If you dont use the logger.info('text',...) format, change this code
def should_handle(node):
parent = node.parent
return node.value in logfunctions and \
isinstance(parent, redbaron.nodes.AtomtrailersNode) and \
node.index_on_parent == 1 and len(parent) >= 2 and \
parent[node.index_on_parent - 1].value == 'logger'
# This should be the formatted text you want
def format(filename, lineno, funcname=None):
return '[%s:%d:%s] ' % (filename, lineno, funcname) \
if funcname else '[%s:%d] ' % (filename, lineno)
# This should remove the formatting to reapply it
def format_remove(s):
match = re.match("\"\[\S+:\d+:\S+] ", s)
if match:
return s[0] + s[match.end():]
else:
return s
# Call this with remove, to remove it before putting it back
# in code repository
def process_file(filename, remove=False):
with open(filename, 'rb') as f:
d = f.read()
ast = redbaron.RedBaron(d)
for node in ast.find_all('name', should_handle):
lineno = node.absolute_bounding_box.top_left.line
funcname = node.parent_find('def')
if funcname:
funcname = funcname.name
node_to_change = node.parent[node.index_on_parent + 1][0].value
node_to_change.value = format_remove(node_to_change.value)
if not remove:
node_to_change.value = node_to_change.value[0] + \
format(filename, lineno, funcname) + node_to_change.value[1:]
data = ast.dumps()
with open(filename, 'wb') as f:
f.write(data)
if __name__ == "__main__":
process_file('demo.py')
@uuip
Copy link

uuip commented Jan 9, 2019

    node_to_change = node.parent[node.index_on_parent + 1][0]
    #self.logger.error("eeeee {}".format(555))
    node_value=str(node_to_change.value)   # treat "eeeee {}".format(555)   as a whole value.
    if not remove:
        node_to_change.value = '"{} {{}}".format({})'.format(format(filename, lineno, funcname),node_value)
    else:
        node_to_change.value = format_remove(node_value)

Your situation only applies to pure strings. I made some improvements on your basis.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment