2

I'm new to Python and I'm trying to log to file and to console, I saw this question: logger configuration to log to file and print to stdout

which was very helpful but I Saw that there is a way to configure an ini file and then use it in every module.

Problem is that it seems that it doesn't take the properties from the ini file and if I don't explicitly define the formatter in the code it uses the default logging without the format that I gave him in the ini file:

    configFolder = os.getcwd() + os.sep + 'Configuration'
    fileConfig(configFolder + os.sep + 'logging_config.ini')
    logger = logging.getLogger(__name__)
    # create a file handler
    handler = logging.FileHandler('logger.log')
    handler.setLevel(logging.INFO)

    # add the handlers to the logger
    logger.addHandler(handler)
    logger.info('hello')

output would be just:

hello

instead of :

2016-08-08 15:16:42,954 - __main__ - INFO - hello

This is my ini file:

[loggers]
keys=root

[handlers]
keys=stream_handler

[formatters]
keys=formatter

[logger_root]
level=INFO
handlers=stream_handler

[handler_stream_handler]
class=StreamHandler
level=INFO
formatter=formatter
args=(sys.stderr,)

[formatter_formatter]
format=%(asctime)s %(name)-12s %(levelname)-8s %(message)s
Community
  • 1
  • 1
Shahar Hamuzim Rajuan
  • 5,610
  • 9
  • 53
  • 91
  • Please include the definition of `fileConfig`. Also, why are you adding a `FileHandler` and setting the level in your code if you already have it defined in your logging config file? – DocZerø Aug 08 '16 at 13:05
  • You are right about setting the level, So I deleted this part. But what do you mean "include the definition of fileConfig"? This is where it's defined: fileConfig(configFolder + os.sep + 'logging_config.ini') – Shahar Hamuzim Rajuan Aug 08 '16 at 13:48
  • Didn't realise you were using the built-in `logging.config.fileConfig`. I suspect you used `from logging.config import *`. – DocZerø Aug 08 '16 at 13:49
  • Normally, the call to `fileConfig` should be sufficient. No need to call add a `FileHandler` as this is what the configuration file is doing (your `stream_handler`) – DocZerø Aug 08 '16 at 13:51

1 Answers1

0

Change formatter=formatter to match the name of your formatter: formatter_formatter

Yusufk
  • 1,055
  • 2
  • 10
  • 15