Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the logging module of python standard library

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article editor for you a detailed introduction of the "python standard library logging module how to use", the content is detailed, the steps are clear, the details are handled properly, I hope this "python standard library logging module how to use" article can help you solve doubts, following the editor's ideas slowly in-depth, together to learn new knowledge.

Question1: how to get the caller (file name, line number, function name)?

When a new log record is added, the _ log method of the Logger class is eventually called, which first creates a LogRecord object. The LogRecord object requires (filename, lineno, funcname) parameter information. This is achieved through the following statement:

Fn, lno, func = self.findCaller () findCaller are as follows: F = currentframe () # f is a frame object, and each method call generates a frame object, which is placed on the program stack. If f is not None: F = f.f_back rv = "(unknown file)", 0, "(unknown function)" while hasattr (f, "f_code"): co = f.f_code # gets the code object, which contains the filename attribute The funcname attribute filename = os.path.normcase (co.co_filename) if filename = = _ srcfile: # _ srcfile is the file name of the module file itself. When the file name is no longer the same, f = f.f_back # gets the frame of the external caller, which is required. Definition of continue rv = (filename, f.f_lineno, co.co_name) break return rvcurrentframe function: def currentframe (): "Return the frame object for the caller's stack frame." Try: raise Exception # throws an exception, which generates a traceback object that contains a frame object. Except: # sys.exc_traceback.tb_frame current frame. The frame return sys.exc_traceback.tb_frame.f_back#sys._getframe (3) called by f_back does not return the current frame,3. Reduce the number of loops, and return the frameif hasattr (sys,'_ getframe') of logger.error (): currentframe = lambda: sys._getframe (3) question 2: level of Logger object How is the father-son relationship realized?

First of all, the logger hierarchical relationship in the logging module is the structure of a tree relationship whose root is' root'.

The root = RootLogger (WARNING) # RootLogger class is a subclass of Logger and has no special function, but the name is defined as' root'. Logger.root = rootLogger.manager = Manager (Logger.root)

When logging.getLogger () is called to get a Logger, it returns' root' if the argument is empty. Otherwise, call the getLogger () method of Manager to get the Logger.

Def getLogger (name=None): "Return a logger with the specified name, creating it if necessary. If no name is specified, return the root logger." If name: return Logger.manager.getLogger (name) else: the definition of getLogger () for return rootManager is as follows: def getLogger (self, name): "" Get a logger with the specified name (channel name), creating it if it doesn't yet exist. This name is a dot-separated hierarchical name, such as "a", "a.b", "a.b.c" or similar. If a PlaceHolder existed for the specified name [i.e. The logger didn't exist but a child of it did], replace it with the created logger and fix up the parent/child references which pointed to the placeholder to now point to the logger. " Rv = None _ acquireLock () try: if name in self.loggerDict: rv = self.loggerDict [name] if isinstance (rv PlaceHolder): ph = rv rv = _ loggerClass (name) rv.manager = self self.loggerDict [name] = rv self._fixupChildren (ph) Rv) self._fixupParents (rv) else: rv = _ loggerClass (name) rv.manager = self self.loggerDict [name] = rv self._fixupParents (rv) finally: _ releaseLock () return rv

The loggerDict dictionary in the Manager object, which stores the mapping between the logger name and the logger object. The PlaceHolder class is a container.

For example, a PlaceHolder object named 'sell'' does not have a logger for 'sell' at first, so logger that begins with' sell' has a reference in this object, such as an existing logger object such as' sell.food','sell.cloth.china'. When you call getLogger () to get a logger that does not exist, such as' level1.level2', first create a logger object named 'level1.level2', which resides in the loggerDict. Then, call _ fixupParents ().

The function of _ fixupParents ():

On the hierarchical chain of this name, find the first logger object, make it the parent, and return it. If the name of the logger object is not on the chain, create a PlaceHolder object (if not) and add yourself to it.

For example, add a logger for 'level1.level2.level3', call _ fixupParents to create a PlaceHolder object named' level1.level2', create a PlaceHolder object named 'level1', and add the logger' level1.level2.level3' to the above two PlaceHolder object containers, and set its parent to 'root'.

In short, _ fixupParents is to point the logger object to the real parent node (the logger object) and add logger itself to all the upper PlaceHolder object containers.

If you get a name that already exists in the loggerDict, and the name corresponds to a previously created PlaceHolder object. First, create a logger object with the corresponding name. Then, call _ fixupChild () to fix the parent of the downstream logger object contained in the PlaceHolder object. Finally, call _ fixupParent (), which has the same effect as the previous step.

The main role of the parent-child hierarchy is that when the propagate property of the logger object has a value of 1 (the default), each logRecord record is passed to the parent logger for processing. This can be done simply by defining the 'root' root logger object, the other logger defining a name, according to the module name, class name, etc., and then binding a NullHandler. Finally, all logRecord will be handed over to 'root' unified processing. This is how multiple modules generate uniform format log.

After reading this, the article "how to use the logging module of the python standard library" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself to understand it. If you want to know more about related articles, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report