I want to write or find a plugin that helps me convert print statements to log statements in Python 3.
Consider a situation: I am writing some code, I want to add a feature based around some API, I quickly write a couple lines of code and add a bunch of print statements here and there that help me in understanding what the current state of the program is.
print("API response", response)
print(val1, val2)
print("I am a string with no variables")
print(f"I am an f-string so I will have {curly} {variables} here and there")
print(traceback.format_exc())
I want to be able to convert all these to log statements:
log.info(f"API response {response}")
log.info(f"{val1} {val2}"4)
log.info("I am a string with no variables")
log.info(f"I am an f-string so I will have {curly} {variables} here and there")
log.error(f"{traceback.format_exc()}")
In case of f-strings
, it is a simple find and replace, but in all other cases, there's a lot of hassle around converting the print statement to a proper format before I can log it.
So far, I have written some custom mappings which use the surround.vim plugin:
"wrap value in bracket with f-string
nmap <leader>w ysib"ysi"}F"if<Esc>
"change print to log.info
nmap <leader>y csflog.info<Esc><leader>w
nmap <leader>wt _ys$}ysa}"If<Esc>_ys$)Ilog.error<Esc>
"maybe add map for direct writing the whole statement?
nmap <leader>yt Ilog.error(f"{traceback.format_exc()}")<Esc>
But they are very limited in usage
Python
than invim
. Simply add a new function to take in args like...(*args)
, and then calllogs.info(" ".join(args))
. And maybe a second function to calllogs.error(" ".join(args))
. Once you have those functions, then usevim
to (e.g.):%s/\<print(/print_log(/c