Search code examples
pythonpython-logging

python after logging.debug() how to view its logrecord


Recently I came across logging in python.

I have the following code in test.py file

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
logger.debug("test Message")

Now, is there any way I can print the resulting Logrecord object generated by logger.debug("test Message") because it's stated in the documentation that

LogRecord instances are created automatically by the Logger every time something is logged

https://docs.python.org/3/library/logging.html#logrecord-objects

I checked saving debug into a variable and print it

test = logger.debug("test Message")
print(test)

the output is NONE

My goal is to check/view the final Logrecord object generated by logging.debug(test.py) in the same test.py by using print() This is for my own understanding.

print(LogrecordObject.__dict__)

So how to get hold of the Logrecord object generated by logger.debug("test Message")


Solution

  • A quick way if you just wish to view the LogRecord attributes, you can specify a subset of them as string replacements in a giant string like below.

    import logging
    
    view_all_logrecord_attributes = """
    asctime - %(asctime)s
    created - %(created)f
    
    filename - %(filename)s
    funcName - %(funcName)s
    levelname - %(levelname)s
    levelno - %(levelno)s
    lineno - %(lineno)d
    message - %(message)s
    module - %(module)s
    msecs - %(msecs)d
    
    name - %(name)s
    pathname - %(pathname)s
    process - %(process)d
    processName - %(processName)s
    relativeCreated - %(relativeCreated)d
    
    thread - %(thread)d
    threadName - %(threadName)s
    """
    
    logging.basicConfig(format= view_all_logrecord_attributes, level=logging.DEBUG)
    logging.debug('Message text here')
    

    The list is from the documentation: https://docs.python.org/3/library/logging.html#logrecord-attributes

    And an example output would be:

    asctime - 2024-02-21 08:42:10,428
    created - 1708465330.428894
    
    filename - <stdin>
    funcName - <module>
    levelname - DEBUG
    levelno - 10
    lineno - 1
    message - Message text here
    module - <stdin>
    msecs - 428
    
    name - root
    pathname - <stdin>
    process - 94365
    processName - MainProcess
    relativeCreated - 749
    
    thread - 8042958848
    threadName - MainThread