2

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()
1

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

One way is to write your own simple logging function as a closure:

def create_logger(log_filename = 'TestLog.log'):
    f = open(log_filename, 'w')

    def logger(text):
        f.write(text + '\n')

    return logger,f.close

logwrite,logclose = create_logger()

def log1():
    print 'log1 called'
    logwrite('log1 result')

def log2():
    print 'log2 called'
    logwrite('log2 result')

log1()
log2()
logclose()

It avoids having to use global, encapsulates the file object, simplifies the call, and enables you to use several different filenames by calling create_logger for each one required. You might, for example, wish to add a date/time stamp to the log message, simply done in one place by enhancing the logger function.

2 Comments

You probably want to open the file in append mode. Otherwise it will overwrite the file at each call.
@wallyk: No it won't. The open is only done once when create_logger is called. The actual write is done by the returned logger function which is then called multiple times.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.