I am fairly new to Python and now trying to use Logging rather that Print to follow and debug my code. The problem is that I am trying to setup Logging parameters using a def inline function and it is not working. I am using def because the parameter list is long and can be reused.
However by trial and error (definitely not by understanding!) I find that the following code works:
def setuplogging():
# logging_example
#import logging
# When setting up logging, define the level using capitals because logging.debug is seen as a function, logging.DEBUG is the level id.
# Create a custom logger
logger = logging.getLogger(__name__) #The variable __name__ contains the dotted name of the current module.
logger.setLevel(logging.DEBUG) #WARM is default
# Create handlers
c_handler = logging.StreamHandler()
f_handler = logging.FileHandler('E:datacomputingsoftwareprogrammingscriptsLOGFILE.log')
c_handler.setLevel(logging.DEBUG)
f_handler.setLevel(logging.DEBUG)
# Create formatters and add it to handlers
c_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
c_handler.setFormatter(c_format)
f_handler.setFormatter(f_format)
# Add handlers to the logger
logger.addHandler(c_handler)
logger.addHandler(f_handler)
logger.info('def This is a test of an info message')
logger.warning('def This is a warning')
logger.error('def This is an error')
import logging
logging.warning('This is a trial of basic logging')
setuplogging()
logging = logging.getLogger(__name__)
logging.info('Script This is a test of an info message')
logging.warning('Script This is a warning')
logging.error('Script This is an error')
However, without the "logging = logging.getLogger(__name__)" after the function call, the last three logging statements in the main script do not do anything. Why is this?
The output I get is doubled - dont know why:
[![Extract from the console log:][1]][1]
[1]: https://i.sstatic.net/4ap6Io5L.png
Thanks in advance for your help.