0

For some reason, the code below generates an empty log file, with no text inside. What am I doing wrong?

import logging

def log_generator(logfilepath='test.log'):

    my_formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    my_logger = logging.getLogger('example_logger')
    my_handler = logging.FileHandler( logfilepath )
    my_handler.setFormatter( my_formatter )
    my_logger.addHandler( my_handler )

    my_logger.info('message 1') # This should be visible in the log file


log_generator() # Execute the log_generator() function

1 Answer 1

3

You need to set level to the logger.

add this line befoure calling info():

my_logger.setLevel(logging.DEBUG)

So your code should look like this:

import logging

def log_generator(logfilepath='test.log'):

    my_formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    my_logger = logging.getLogger('example_logger')
    my_handler = logging.FileHandler(logfilepath)
    my_handler.setFormatter( my_formatter )
    my_logger.addHandler( my_handler )
    my_logger.setLevel(logging.DEBUG)
    my_logger.info('message 1') # This should be visible in the log file


log_generator()

Which will five you the output:

john-the-ripper@john-the-ripper:/tmp$ more test.log 
2014-08-07 10:20:23,665 INFO message 1

Updated:

From the docs:

 The INFO message doesn’t appear because the default level is WARNING.
Sign up to request clarification or add additional context in comments.

2 Comments

I thought the default level was INFO on up. Is this not true?
@KronoS default is warning

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.