print line number and source filename

Peng Yu pengyu.ut at gmail.com
Wed Jun 23 23:07:18 EDT 2010


On Tue, Jun 22, 2010 at 12:13 PM, Stephen Hansen
<me+list/python at ixokai.io> wrote:
> On 6/22/10 9:44 AM, Peng Yu wrote:
>> Also, always importing the inspect module and getting the frame and
>> accessing the lineno from the frame is not very convenient to type. Is
>> there a shorter way to access the line number (for example, in C++ and
>> perl, __LINE__ can be used to access line number, which is much more
>> convenient than the way that I found in python).
>
> This all seems to be reinventing the wheel. Have you seen the logging
> module?
>
> Given this toy file:
>
> ---- begin -----
> import logging
> logging.basicConfig(level=logging.DEBUG,format="%(asctime)s
> %(levelname)-5.5s [%(name)s %(module)s:%(funcName)s:%(lineno)d]
> %(message)s")
>
> def run():
>    x = 5
>    logging.debug("X = %d" % x)
>
> run()
> ----- end -----
>
> 2010-06-22 10:12:07,907 DEBUG [root test:run:6] X = 5
>
> It outputs exact time, type of log message, the name of the logger
> (That's the 'root' -- you can skip if you only use one), the exact
> module (test.py), function (run) and line (6).

I tried to put the above code in a module. Say in a.b.__init__.py

%(module)s only print to "__init__". However, I need the fullname
a.b.__init__. I looked at the manual, but I don't see what format
string I should supply. Would you please let me know?

-- 
Regards,
Peng



More information about the Python-list mailing list