Python Custom FileHandler in logging.conf

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bishaq
    New Member
    • Aug 2016
    • 3

    Python Custom FileHandler in logging.conf

    I have added a custom File handler to create a log file append with date and time in a specified directory. Everything works fine if I have my main.py and logconfig.py and MyFileHandler.p y in the same directory. As soon as I move my logconfig.py and MyFileHandler.p y in a different directory, my code starts throwing following error.
    *************** *************** *************** ***************
    *************** *** Error *************** *************** *****
    Traceback (most recent call last):
    File "C:\Python\Pyth on36\lib\loggin g\config.py", line 143, in _install_handle rs
    klass = eval(klass, vars(logging))
    File "<string>", line 1, in <module>
    NameError: name 'MyFileHandler' is not defined

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
    File "C:\Program Files (x86)\JetBrains \PyCharm Community Edition 2016.2\helpers\ pycharm\utrunne r.py", line 153, in <module>
    modules = [loadSource(a[0])]
    File "C:\Program Files (x86)\JetBrains \PyCharm Community Edition 2016.2\helpers\ pycharm\utrunne r.py", line 65, in loadSource
    module = imp.load_source (moduleName, fileName)
    File "C:\Python\Pyth on36\lib\imp.py ", line 172, in load_source
    module = _load(spec)
    File "<frozen importlib._boot strap>", line 693, in _load
    File "<frozen importlib._boot strap>", line 673, in _load_unlocked
    File "<frozen importlib._boot strap_external> ", line 656, in exec_module
    File "<frozen importlib._boot strap>", line 222, in _call_with_fram es_removed
    File "C:\Users\bilal \workspace\Pych armProjects\Sel unium_Automatio n\Tests\SmokeTe st.py", line 9, in <module>
    from Selunium_Automa tion.WebPages.P ages import Pages
    File "C:\Users\bilal \workspace\Pych armProjects\Sel unium_Automatio n\WebPages\Page s.py", line 1, in <module>
    from Selunium_Automa tion.Locators.H omePgLocator import *
    File "C:\Users\bilal \workspace\Pych armProjects\Sel unium_Automatio n\Locators\Home PgLocator.py", line 1, in <module>
    from Selunium_Automa tion.Lib.PageEl ements import PageElements
    File "C:\Users\bilal \workspace\Pych armProjects\Sel unium_Automatio n\Lib\PageEleme nts.py", line 3, in <module>
    from Selunium_Automa tion.Utilities. WebDriverSetup import Web
    File "C:\Users\bilal \workspace\Pych armProjects\Sel unium_Automatio n\Utilities\Web DriverSetup.py" , line 1, in <module>
    from Selunium_Automa tion.Utilities. WebDriverFactor y import WebDriverFactor y
    File "C:\Users\bilal \workspace\Pych armProjects\Sel unium_Automatio n\Utilities\Web DriverFactory.p y", line 3, in <module>
    from Selunium_Automa tion.LogConfig. LogConfig import Logger
    File "C:\Users\bilal \workspace\Pych armProjects\Sel unium_Automatio n\LogConfig\Log Config.py", line 16, in <module>
    @singleton
    File "C:\Users\bilal \workspace\Pych armProjects\Sel unium_Automatio n\LogConfig\Log Config.py", line 13, in singleton
    return get_instance()
    File "C:\Users\bilal \workspace\Pych armProjects\Sel unium_Automatio n\LogConfig\Log Config.py", line 10, in get_instance
    instances[cls] = cls()
    File "C:\Users\bilal \workspace\Pych armProjects\Sel unium_Automatio n\LogConfig\Log Config.py", line 20, in __init__
    logging.config. fileConfig(log_ file_path, disable_existin g_loggers=False )
    File "C:\Python\Pyth on36\lib\loggin g\config.py", line 84, in fileConfig
    handlers = _install_handle rs(cp, formatters)
    File "C:\Python\Pyth on36\lib\loggin g\config.py", line 145, in _install_handle rs
    klass = _resolve(klass)
    File "C:\Python\Pyth on36\lib\loggin g\config.py", line 94, in _resolve
    found = __import__(used )
    ImportError: No module named 'MyFileHandler'
    -----------------------------------------------------------
    #Here is MyFileHandler.

    import logging
    *************** *************** *************** ***************
    *************** *MyFileHandler. py *************** ***********
    # import random
    # import os
    from datetime import datetime
    class MyFileHandler(l ogging.FileHand ler):
    def __init__(self, filename, path, mode):
    self.filename = datetime.now(). strftime(filena me + '%H_%M_%d_%m_%Y .log')
    super(MyFileHan dler, self).__init__( path + "/" + self.filename, mode)

    *************** *************** *************** *************** Config File:
    [loggers]
    keys=root,examp leApp

    [handlers]
    keys=fileHandle r, consoleHandler

    [formatters]
    keys=myFormatte r

    [logger_root]
    level=CRITICAL
    handlers=consol eHandler

    [logger_exampleA pp]
    level=DEBUG
    handlers=fileHa ndler
    qualname=exampl eApp

    [handler_console Handler]
    class=StreamHan dler
    level=DEBUG
    formatter=myFor matter
    args=(sys.stdou t,)

    [handler_fileHan dler]
    class=MyFileHan dler.MyFileHand ler
    formatter=myFor matter
    args=('Automati on','./', 'a')

    [formatter_myFor matter]
    format=%(asctim e)s - %(name)s - %(levelname)s - [%(filename)s:%( funcName)10s()] %(message)s"
    datefmt=

    below is the function I am using to call logger in other modules
    import logging.config
    from os import path
    *************** *************** *************** **************
    *************** *******LogConfi g.py*********** **************
    def singleton(cls):
    instances = {}

    def get_instance():
    if cls not in instances:
    instances[cls] = cls()
    return instances[cls]

    return get_instance()


    @singleton
    class Logger:
    def __init__(self):
    log_file_path = path.join(path. dirname(path.ab spath(__file__) ), 'log.conf')
    logging.config. fileConfig(log_ file_path, disable_existin g_loggers=False )
    self.logr = logging.getLogg er('exampleApp' )

    -----------------------
    Any help would be greatly appreciated?
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    Python has a specific search path stored in a list. You can see it with
    Code:
    import sys
    print sys.path
    ##
    ## You can add other directories to be searched with
    sys.path.append("/the/new/directory")

    Comment

    • bishaq
      New Member
      • Aug 2016
      • 3

      #3
      Originally posted by dwblas
      Python has a specific search path stored in a list. You can see it with
      Code:
      import sys
      print sys.path
      ##
      ## You can add other directories to be searched with
      sys.path.append("/the/new/directory")

      Can you please be specific as I am new to Python

      Comment

      • dwblas
        Recognized Expert Contributor
        • May 2008
        • 626

        #4
        There is no way to tell what "specific" means as the original answer was specific, i.e. everything you need to do. Please post a simple example of what you have tried to add the directory where you moved the programs to the Python search path.

        Comment

        Working...