Ways to get line numbers and function names using the SYS template and the logging module in Python

Source: Internet
Author: User
Tags time in milliseconds
For Python, there are two problems that have plagued me these days:
There is no way to get the current line number and function name directly in 1.python. This is a question raised in the forum, and the bottom group is just guessing why Python does not offer __line__ and __func__ like __file__, but it does not find a solution at the end.
2. If a function does not know its name, how can it recursively invoke itself. This is a colleague of mine asked me, in fact, also get the function name, but it was also not answered.


But tonight! All the questions have an answer.
It's all going to be from me. In the Python logging module, the format in logging has the following options:

Copy the Code code as follows:


% (name) s name of the logger (logging channel)
% (Levelno) s Numeric logging level for the message (DEBUG, INFO,
WARNING, ERROR, CRITICAL)
% (levelname) s Text logging level for the message ("DEBUG", "INFO",
"WARNING", "ERROR", "CRITICAL")
% (pathname) s full pathname of the source file where the logging
Call is issued (if available)
% (filename) s filename portion of pathname
% (module) s module (name portion of filename)
% (Lineno) d Source Line number where the logging call is issued
(if available)
% (funcName) s Function name
% (created) f time when the LogRecord is created (Time.time ()
return value)
% (asctime) s textual time when the LogRecord is created
% (msecs) d millisecond portion of the creation time
% (relativecreated) d time in milliseconds when the LogRecord is created,
Relative to the time of the logging module was loaded
(typically at application startup time)
% (thread) d thread ID (if available)
% (threadname) s Thread name (if available)
% (process) d process ID (if available)
% (message) s The result of Record.getmessage (), computed just as
The record is emitted

In other words, logging is able to get to the caller's line number and function name, that can also get their own line number and function name it?
Let's look at the source code, the main parts are as follows:

Copy the Code code as follows:


Def currentframe ():
"" "Return the frame object for the caller ' s stack frame." "
Try
Raise Exception
Except
return Sys.exc_info () [2].tb_frame.f_back
def findcaller (self):
"""
Find the stack frame of the caller so that we can note the source
File name, line number and function name.
"""
f = currentframe ()
#On Some versions of IronPython, Currentframe () returns None if
#IronPython isn ' t run with-x:frames.
If f is not None:
f = f.f_back
RV = "(Unknown file)", 0, "(Unknown function)"
While Hasattr (F, "F_code"):
CO = F.f_code
filename = os.path.normcase (co.co_filename)
if filename = = _srcfile:
f = f.f_back
Continue
RV = (Co.co_filename, F.f_lineno, Co.co_name)
Break
Return RV
Def _log (self, level, MSG, args, Exc_info=none, Extra=none):
"""
Low-level logging routine which creates a logrecord and then calls
All the handlers of this logger to handle the record.
"""
If _srcfile:
#IronPython doesn ' t track Python frames, so Findcaller throws an
#exception on some versions of IronPython. We trap it.
#IronPython can use logging.
Try
FN, Lno, func = Self.findcaller ()
Except ValueError:
FN, Lno, func = "(Unknown file)", 0, "(Unknown function)"
Else
FN, Lno, func = "(Unknown file)", 0, "(Unknown function)"
If Exc_info:
If not isinstance (Exc_info, tuple):
Exc_info = Sys.exc_info ()
Record = Self.makerecord (Self.name, Level, FN, Lno, msg, args, Exc_info, func, extra)
Self.handle (Record)

I'll simply explain that by throwing an exception in the Currentframe function, and then finding the message by looking up the way. which

Copy the Code code as follows:


RV = (Co.co_filename, F.f_lineno, Co.co_name)

The three values are file name, line number, function name, respectively. (You can go to http://docs.python.org/library/sys.html to see a description of several system functions in the code)
OK, if you have read the source code, then get the current location of the line number and the function name is very clear, it is as follows:

Copy the Code code as follows:


#!/usr/bin/python
#-*-Coding:utf-8-*-
'''
#=============================================================================
# FileName:xf.py
# Description: Gets the line number and function name of the current position
# version:1.0
#=============================================================================
'''
Import Sys
Def get_cur_info ():
"" "Return the frame object for the caller ' s stack frame." "
Try
Raise Exception
Except
f = sys.exc_info () [2].tb_frame.f_back
Return (F.f_code.co_name, F.f_lineno)

Def callfunc ():
Print Get_cur_info ()


if __name__ = = ' __main__ ':
Callfunc ()


The input results are:
Copy CodeThe code is as follows:

(' Callfunc ', 24)


Meet Expectations ~ ~
Haha, ok! Now it's time to stop complaining about not having line numbers and function names.

=============================================================================
Later found that there can actually be a simpler way, as follows:
Copy the Code code as follows:

Import Sys
Def get_cur_info ():
Print Sys._getframe (). F_code.co_name
Print Sys._getframe (). F_back.f_code.co_name
Get_cur_info ()


The result of the call is:
Copy CodeThe code is as follows:

Get_cur_info
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.