Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging to two files with different settings

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') 
like image 221
marw Avatar asked Jun 27 '12 17:06

marw


People also ask

What is logging getLogger (__ Name __)?

getLogger(name) is typically executed. The getLogger() function accepts a single argument - the logger's name. It returns a reference to a logger instance with the specified name if provided, or root if not. Multiple calls to getLogger() with the same name will return a reference to the same logger object.

What is a root logger Python?

On top of the hierarchy is the root logger, which can be accessed via logging. root. This logger is called when methods like logging. debug() is used. By default, the root log level is WARN, so every log with lower level (for example via logging.info("info") ) will be ignored.


1 Answers

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') 
like image 71
eos87 Avatar answered Nov 08 '22 23:11

eos87