Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在定制的python logger中获取进程、线程名、levelname_Python_Python 3.x_Python 2.7_Wxpython_Ironpython - Fatal编程技术网

如何在定制的python logger中获取进程、线程名、levelname

如何在定制的python logger中获取进程、线程名、levelname,python,python-3.x,python-2.7,wxpython,ironpython,Python,Python 3.x,Python 2.7,Wxpython,Ironpython,我正在开发定制的记录器程序,根据需要,我需要获取被调用函数中的进程、线程和对象名称(在下面的示例中,其obj需要在get_configured_logger函数中获取)以及obj所属的类名。如下面代码中的注释所示,请给出一些实现此目的的想法 import logging, logging.handlers from logging import StreamHandler, Formatter class A: def get_configured_logger(self,name):

我正在开发定制的记录器程序,根据需要,我需要获取被调用函数中的进程、线程和对象名称(在下面的示例中,其obj需要在get_configured_logger函数中获取)以及obj所属的类名。如下面代码中的注释所示,请给出一些实现此目的的想法

import logging, logging.handlers
from logging import StreamHandler, Formatter
class A:
  def get_configured_logger(self,name):
      logger = logging.getLogger(name)
      if (len(logger.handlers) == 0):                
                FORMAT = "%(process)s %(thread)s:-(asctime)s - %(name)s - %(levelname)s - %(message)-%(module)"

                #print 'process:',process
                #print 'thread:',thread
                #print 'levelname:',levelname
                #print  'Module:',(name portion of filename).

                #print 'obj:,'name of the object(Eg:obj),current function( Eg: get_configured_logger) called by' 
                #print 'class name:(obj is instance of class)' 
                formatter = logging.Formatter(fmt=FORMAT)                                 
                handler = logging.StreamHandler()
                handler.setFormatter(formatter)
                logger.addHandler(handler)
                logger.setLevel(logging.DEBUG)        
      return logger

if __name__=="__main__":
    obj=A()
    logger = obj.get_configured_logger("DEMO")
    logger.debug("TEST")
谢谢

hema

线程名称 描述了访问当前
线程
的简单界面,然后您可以使用其属性获得线程名称

然后,您可以使用:

import threading
threading.current_thread().name
要知道这不是唯一的

进程名称 没有简单的方法获取进程名称,因为这取决于您使用的操作系统。但是,您可以通过以下操作获取进程ID(
pid
):


也就是说,除非您正在使用
多处理
模块并启动子流程,在这种情况下,您可以使用
多处理
模块,该模块提供的界面与
线程
模块的界面非常相似。

将当前进程/线程名称添加到日志消息中,您可以在格式字符串中指定:

%(processName)s %(threadName)s
要将它们作为字符串获取,请执行以下操作:

process_name = multiprocessing.current_process().name
thread_name = threading.current_thread().name

为了完整起见,我想添加
ident
属性,以获取线程的标识符。对于当前进程,我通常使用
os.getpid()
process_name = multiprocessing.current_process().name
thread_name = threading.current_thread().name