1

I know this question been asked twice now in StackOverflow, but nobody answers yet the question.

Here's my code:

logging.basicConfig(filename="logfile.log", filemode='w',
         format='%(asctime)s:%(levelname)s:%(message)s', datefmt='%m/%d/%Y %H:%M:%S')
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical error message')

Output console is EMPTY. Only the logfile.log has the log strings. But when I remove the filename attribute, it started showing the console. I want to show in console and write in my log file. What do I miss? Please answer with code. I read the documentation twice or thrice already. Thank you.

engrbugs
  • 13
  • 2
  • You can't do what you want with just `basicConfig()`: it really is just that basic, and limits the amount of handlers (read: output channels) to one. Hence you have to go another route. – 9769953 Feb 26 '19 at 14:01
  • Perhaps [this section in the logging cookbook, on multiple handlers](https://docs.python.org/3/howto/logging-cookbook.html#logging-to-multiple-destinations) has what you want. – 9769953 Feb 26 '19 at 14:04
  • Possible duplicate of the question https://stackoverflow.com/questions/13733552/logger-configuration-to-log-to-file-and-print-to-stdout. – kosist Feb 26 '19 at 14:10
  • 1
    Possible duplicate of [logger configuration to log to file and print to stdout](https://stackoverflow.com/questions/13733552/logger-configuration-to-log-to-file-and-print-to-stdout) – kosist Feb 26 '19 at 14:11

1 Answers1

1

Just get a handle to the logger and add the StreamHandler and the FileHandler

import logging

logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s")
logger = logging.getLogger()

fileHandler = logging.FileHandler("{0}/{1}.log".format(logPath, fileName))
fileHandler.setFormatter(logFormatter)
logger.addHandler(fileHandler)

consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
logger.addHandler(consoleHandler)
frankegoesdown
  • 1,898
  • 1
  • 20
  • 38