2

I have configured logging in logging.config file. I have created a class where I access this configuration file, enable/disable the logger, and log some Info messages. I am importing this class in all the modules where I need to do some logging. When I try to log to a file, I get this error message. I am not able to understand what this error means.

File "/usr/local/lib/python3.6/configparser.py", line 959, in getitem raise KeyError(key) KeyError: 'formatters'

logging.config
[loggers]
keys=root

[handlers]
keys=fileHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=INFO
handlers=fileHandler

[handler_fileHandler]
class=FileHandler
level=INFO
formatter=simpleFormatter
args=('example.log','a')

[formatter_simpleFormatter]
class=logging.Formatter
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=

#Log.py
import logging.config
class Monitor(object):

    fileName = path.join(path.split(path.dirname(path.abspath(__file__)))[0], "logging.config") 
    print (fileName) #prints /usr/local/lib/python3.6/site-packages/myproject-0.0.1-py3.6.egg/MyPackageName/logging.config
    logging.config.fileConfig(fileName)
    logger = logging.getLogger('root') 
    logger.disabled = False

    @staticmethod
    def Log(logMessage):
        Monitor.logger.info(logMessage)

#sub.py
import Monitor
class Example

def simplelog(self,message):
        Monitor.Log("Logging some  message here")
        #call some function here
        Monitor.Log("Logging some other messages here for example")
user2301
  • 1,857
  • 6
  • 32
  • 63
  • 1
    Does the file `fileName` actually exist and can your program actually open it? I see that same error if I try to make the fileconfig call and pass in a non-existent file. – Tom Dalton Dec 04 '17 at 15:46
  • Yeah, The fileName actually exist. It is placed under the package where I have other modules and config files. Should I set the permission to open and read the file? – user2301 Dec 04 '17 at 15:59
  • I would make sure your program can actually open and read that file - e.g. use an `f = open(...); print(f.read())` to check. – Tom Dalton Dec 04 '17 at 21:41
  • Duplicate of https://stackoverflow.com/questions/23161745/python-logging-file-config-keyerror-formatters – Dumitriu Sebastian Oct 11 '18 at 13:18

1 Answers1

1

I had similar issues when I tried to load config from a python script that was not on the project root directory. and what I figured out was that:

logging.config.fileConfig is dependent on configparser and have issues with initializing with absolute path. Try relative path.

Replace

    fileName = path.join(path.split(path.dirname(path.abspath(__file__)))[0], "logging.config") 

with some thing like:

    ## get path tree from project root and replace children from root with ".."
    path_rslv = path.split(path.dirname(path.abspath(__file__)))[1:] 
    fileName = path.join(*[".." for dotdot in range(len(path_rslv)], "logging.config") 
dropyourcoffee
  • 318
  • 1
  • 5
  • 13