1

I want to save my results as a log file, so I am thinking to import logging module. I understand that to output a file, the code is very straightforward.

logging.basicConfig(filename='logger.log', level=logging.INFO)
logging.debug('debug message')
logging.info('info message')
logging.warn('warn message')
logging.error('error message')
logging.critical('critical message')

However, what if I want to output multiple log files? for example, in the following for loop, each iteration will output a log file, how should I do this?

for i in range(1,10):
  print (i)
  #output a log file to save I value

I tried to use these code, but it's not working.

for i in range(1,10):
    filename = str.format('mylog%d.txt' % i)
    logging.basicConfig(format=log_fmt, level=logging.DEBUG, filename=filename)

    logging.debug('This is debug message')
    logging.info('This is info message')
    logging.warning('This is warning message')
1

2 Answers 2

1

You're using the format function of strings incorrectly. You're trying to use string interpolation, which is an entirely different method of formatting strings. You should try something like this:

filename = 'mylog{0}.txt'.format(i)

The {0} explicitly states that you should take the first value passed to format. You could leave it as {} if you'd like - it makes no real difference.

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

1 Comment

thx, but still, it only create one log file, and all the results are showing in this single file.
1
  1. About file name:

    filename = str.format('mylog%d.txt' % i)
    

    is equal to:

    filename = 'mylog%d.txt' % i
    
  2. For output to multiple files you can use multiple handlers.

    Logging class that handle logging.

    root_logger = logging.getLogger()
    

    Return you root handler. You can add or remove handlers to logger.

    root_logger.handlers
    

    Contains list of handlers of root logger.

    first = root_logger.handlers[0]
    first.close()
    root_logger.removeHandler(first)
    

    remove first handler.

    new_handler = logging.FileHandler(file_name)
    formatter = logging.Formatter('%(asctime)s ' + ' %(message)s', '%H:%M:%S')
    new_handler.setFormatter(formatter)
    root_logger.addHandler(new_handler) 
    

    Add new formatter to root_handler. You can output log to any files at the same time.

For more info read:

Comments

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.