0

I am trying to get my head around how to use the Logging module in Python.

I have the below main code :

import logging
import First
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(levelname)s %(message)s',filename=r'C:\Users\bhatsubh\Desktop\Everything\Codes\Python\Logs\automation.log',filemode='a')
logging.debug('A debug message')
logging.info('Some information')
logging.warning('A shot across the bows')
logging.error('Committed a blunder')
obj = First.Demo("Subhayan",75000)
print (obj.getSal())

The First.py module contains the below code:

class Demo:
    def __init__(self,Name,salary):
        logging.info("Inside Demo init")
        self.name = Name
        self.salary = salary
    def getSal(self):
        logging.info("Inside Demo getSal")
        sal = self.salary * 100
        return sal

Now is there someway in which i can import the module logging at the top level of my module file and then use it in the rest of the calls without importing it again in every other file.?

Thanks a lot in advance for any explanations.

Subhayan Bhattacharya
  • 5,407
  • 7
  • 42
  • 60

1 Answers1

0

Really I would suggest just importing in both files. How Python handles imports is explained here

Otherwise if you really want to then you can do it like so.

First.py

math = None # declare a name for your module

def func():
    print(math.pi)

main.py

import First
import math # using math module as example

test2.math = math
test2.func()

Now the issue with this is that First is now dependent on having it's math attribute set. If this is a problem then you can change it to.

def func():
    print(math.pi)

if __name__ == '__main__':
    import math
else:
    math = None
Community
  • 1
  • 1
Steven Summers
  • 5,079
  • 2
  • 20
  • 31