HAO CHEN
HAO CHEN

Reputation: 1319

create multiple log files python

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

Upvotes: 1

Views: 8396

Answers (2)

Some
Some

Reputation: 514

  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:

Upvotes: 1

wpercy
wpercy

Reputation: 10090

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.

Upvotes: 1

Related Questions