2

I am having some problem with the python logging module. In the following I create a "logger" which I will use later in my code. Here, I am using only the FileHandler but I see that when I log some message to this logger they also appear on the console. Printing to console makes my whole program slow.

Following is the code:

  logger = logging.getLogger("Design")
  logger.setLevel(logging.DEBUG)

  #create a file handler which logs all INFO, DEBUG, ERROR messages

  fh = logging.FileHandler('Design.log', mode='w')

  fmt = logging.Formatter('[%(levelname)s] %(message)s')       

  fh.setFormatter(fmt)

 #adding the handlers to logger
  logger.addHandler(fh)
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
boppu
  • 135
  • 2
  • 3
  • 9

2 Answers2

7

You are missing logger.handlers = []

logger = logging.getLogger("Design")
logger.setLevel(logging.DEBUG)
logger.handlers = []

#create a file handler which logs all INFO, DEBUG, ERROR messages

fh = logging.FileHandler('Design.log', mode='w')

fmt = logging.Formatter('[%(levelname)s] %(message)s')       

fh.setFormatter(fmt)

#adding the handlers to logger
logger.addHandler(fh)

Edit

Add this option if you have previously set up basicConfig()

logger.propagate = False
jayant
  • 2,349
  • 1
  • 19
  • 27
  • 1
    I tried setting "logger.handlers= []", but it still does the same. – boppu Dec 15 '15 at 12:59
  • Do I need to reset default basicConfig? – boppu Dec 15 '15 at 13:40
  • @boppu in that case take a look at this answer http://stackoverflow.com/a/2267567/1517864. Editted my answer accordingly – jayant Dec 15 '15 at 14:14
  • 1
    logger.propagate works. Thanks. I do have one more question, is there any way to print multiple lines to logger at once. I currently, print to a string and then I log the string at once to logger. – boppu Dec 15 '15 at 16:08
0

What caused this error for me was the import statement.

Working Statments

import logging
fh = logging.FileHandler('error.log', mode='w')
logger = getLogger(__name__)

ERROR ON import *

from logging import *
fh = logging.FileHandler('error.log', mode='w')
logger = getLogger(__name__)

and did not change my code so I needed to be

from logging import *
fh = FileHandler('error.log', mode='w')
logger = getLogger(__name__)
JayRizzo
  • 3,234
  • 3
  • 33
  • 49