pythonlogging

Add a "log" for a single function


I need to debug some legacy code and I only want to print some information to a file that will not disturb any other places in the codebase. The most crude way I have found so far is something like:

def my_func():
    f = open('/tmp/log.txt', 'a') # help with logging stuff
    f.write('Here is my crude local logger.')
    # some code
    logger.log('Hello') # our 'Normal logger' that goes to Splunk
                        # so I don't think I can modify this 
                        # safely without side-effects?

However, I like all the 'extra' stuff that the logging module adds in, such as line numbers, time, functions, etc. What might be the best way to add in a local logger to do what a normal logger might do?


Solution

  • It is possible to create a local logger using the very same logging module:

    import logging
    
    def my_func():
        local_logger = logging.getLogger('my_func_logger')
        # set custom handlers on local_logger, maybe even control creation with a function
        # or some env vars
    
        # some code
    
        local_logger.log('Hello')