How to get process, thread name, level name in python custom log

I am developing a custom registration program, in accordance with the requirement, I need to get the process, thread and object name. Inside the called function (In the example below, its obj must be obtained inside the get_configured_logger function) and the name of the class to which obj belongs. as shown below with comments, please give some ideas to achieve this.

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") 

thanks

Hema

+4
source share
2 answers

To add the current process / thread name to the log message, which you can specify in the format string:

 %(processName)s %(threadName)s 

To get them as strings:

 process_name = multiprocessing.current_process().name thread_name = threading.current_thread().name 
+15
source

Topic Title

The documentation describes a simple interface for accessing the current Thread , then you can use its name to have the name Thread.

Then you can use:

 import threading threading.current_thread().name 

Remember that it is not unique.

Process name

There is no easy way to get the process name, as it depends on the OS you are using. However, you can get the process id ( pid ):

 import os os.getpid() 

That is, if you do not use the multiprocessing module and do not start the subprocesses, in this case you can use the multiprocessing module, which represents an interface close to the interface of the Threading module.

+4
source

Source: https://habr.com/ru/post/1440977/


All Articles