Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to log method calls in Python?

Tags:

We can code out some sort of logging decorator to echo function/method calls like the following:

def log(fn):     ...  @log def foo():     ...  class Foo(object):     @log     def foo(self):         ...      @log     def bar(self, a, b):         ...      @log     def foobar(self, x, y, z):         ... 

But what if we are like to log method calls without putting that many @log in front of each meth definition? Is there some way to just put one decorator above a class definition to make all its method calls decorated/logged? Or are there some other better and interesting ways to do that instead of decorator?

like image 950
Drake Guan Avatar asked Feb 24 '11 11:02

Drake Guan


People also ask

How do you add logs to a function in Python?

You can configure logging as shown above using the module and class functions or by creating a config file or a dictionary and loading it using fileConfig() or dictConfig() respectively. These are useful in case you want to change your logging configuration in a running application.

Does Python logging use log4j?

log4j is a popular logging package written in Java. log4j has been ported to the C, C++, C#, Perl, Python, Ruby, and Eiffel languages.


1 Answers

This might be overkill, but there is a trace function facility that will inform you of a great deal of activity within your program:

import sys  def trace(frame, event, arg):     if event == "call":         filename = frame.f_code.co_filename         if filename == "path/to/myfile.py":             lineno = frame.f_lineno             # Here I'm printing the file and line number,              # but you can examine the frame, locals, etc too.             print "%s @ %s" % (filename, lineno)     return trace  sys.settrace(trace) call_my_function() sys.settrace(None) 
like image 144
Ned Batchelder Avatar answered Oct 07 '22 00:10

Ned Batchelder