Logging to two files with different settings

PythonPython 3.xLoggingLogfile

Python Problem Overview


I am already using a basic logging config where all messages across all modules are stored in a single file. However, I need a more complex solution now:

  • Two files: the first remains the same.
  • The second file should have some custom format.

I have been reading the docs for the module, bu they are very complex for me at the moment. Loggers, handlers...

So, in short:

How to log to two files in Python 3, ie:

import logging
# ...
logging.file1.info('Write this to file 1')
logging.file2.info('Write this to file 2')

Python Solutions


Solution 1 - Python

You can do something like this:

import logging
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')


def setup_logger(name, log_file, level=logging.INFO):
    """To setup as many loggers as you want"""

    handler = logging.FileHandler(log_file)        
    handler.setFormatter(formatter)
    
    logger = logging.getLogger(name)
    logger.setLevel(level)
    logger.addHandler(handler)

    return logger

# first file logger
logger = setup_logger('first_logger', 'first_logfile.log')
logger.info('This is just info message')

# second file logger
super_logger = setup_logger('second_logger', 'second_logfile.log')
super_logger.error('This is an error message')

def another_method():
   # using logger defined above also works here
   logger.info('Inside method')

Solution 2 - Python

def setup_logger(logger_name, log_file, level=logging.INFO):
    l = logging.getLogger(logger_name)
    formatter = logging.Formatter('%(message)s')
    fileHandler = logging.FileHandler(log_file, mode='w')
    fileHandler.setFormatter(formatter)
    streamHandler = logging.StreamHandler()
    streamHandler.setFormatter(formatter)

    l.setLevel(level)
    l.addHandler(fileHandler)
    l.addHandler(streamHandler)    


setup_logger('log1', txtName+"txt")
setup_logger('log2', txtName+"small.txt")
logger_1 = logging.getLogger('log1')
logger_2 = logging.getLogger('log2')

    
    

logger_1.info('111messasage 1')
logger_2.info('222ersaror foo')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarwView Question on Stackoverflow
Solution 1 - Pythoneos87View Answer on Stackoverflow
Solution 2 - PythonGankView Answer on Stackoverflow