Q:

Multiple functions to write into a single log file using Python

I have a Python file with contains a few functions. When the "main" function runs, it runs through the functions. Each function needs to write some text to the same single log file.
I have written the following codes. The file handler is declared here as global in each function. I am wondering if there is a better way to achieve this?
LOG_FILE_NAME = 'TestLog.log'
f = None

def log1():
    global f
    print 'log1 called'
    f.write('log1 result' + '\n')

def log2():
    global f
    print 'log2 called'
    f.write('log2 result' + '\n')

logFileDir = LOG_FILE_NAME
f = open(logFileDir, 'w')
log1()
log2()
f.close()

A:

Expanding Tom Dalton's link (docs.python.org/2/howto/logging.html#logging-to-a-file):
import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

will write this too a file
DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too

in your example, you could use a global logger, and each function could invoke it
import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)

def log1():
    logging.info('log1')

def log2():
    logging.info('log2')

if __name__ == '__main__':
    log1()
    log2()

if you wanted multiple loggers, you can use logging.getLogger(), there is plenty of flexibility with the logging module, check out the documentation (in the link).

