Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method logging in Python

Tags:

python

logging

I'd like something equivalent to

calling method: $METHOD_NAME
args:           $ARGS
output:         $OUTPUT

to be automatically logged to a file (via the logging module, possibly) for every (user-defined) method call. The best solution I can come up with is to write a decorator that will do this, and then add it to every function. Is there a better way?

Thanks

like image 884
mellort Avatar asked Dec 28 '22 10:12

mellort


1 Answers

You could look at the trace module in the standard library, which

allows you to trace program execution, generate annotated statement coverage listings, print caller/callee relationships and list functions executed during a program run. It can be used in another program or from the command line.

You can also log to disk:

import sys
import trace

# create a Trace object, telling it what to ignore, and whether to
# do tracing or line-counting or both.
tracer = trace.Trace(
    ignoredirs=[sys.prefix, sys.exec_prefix],
    trace=0,
    count=1)

# run the new command using the given tracer
tracer.run('main()')

# make a report, placing output in /tmp
r = tracer.results()
r.write_results(show_missing=True, coverdir="/tmp")
like image 198
miku Avatar answered Jan 05 '23 15:01

miku