How to do it...

First, we create a new Python module into which we place two new classes. The first class is very simple and defines the logging levels. This is basically an enumeration:

class LogLevel: 
'''Define logging levels.'''
OFF = 0
MINIMUM = 1
NORMAL = 2
DEBUG = 3

The second class creates a log file by using the passed-in full path of the file name and places this into a logs folder. On the first run, the logs folder might not exist, so the code automatically creates the folder:

import os, time
from datetime import datetime
class Logger:
''' Create a test log and write to it. '''
#-------------------------------------------------------
def __init__(self, fullTestName, loglevel=LogLevel.DEBUG):
testName = os.path.splitext(os.path.basename(fullTestName))[0]
logName = testName + '.log'

logsFolder = 'logs'
if not os.path.exists(logsFolder):
os.makedirs(logsFolder, exist_ok = True)

self.log = os.path.join(logsFolder, logName)
self.createLog()

self.loggingLevel = loglevel
self.startTime = time.perf_counter()

#------------------------------------------------------
def createLog(self):
with open(self.log, mode='w', encoding='utf-8') as logFile:
logFile.write(self.getDateTime() +
' *** Starting Test *** ')
logFile.close()

In order to write to our log file, we use the writeToLog() method. Inside the method, the first thing we do is check whether the message has a logging level higher than the limit we set our desired logging output to. If the message has a lower level, we discard it and immediately return from the method.

If the message has the logging level that we want to display, we then check whether it starts with a newline character, and if it does, we discard the newline by slicing the method starting at index 1, using Python's slice operator (msg = msg[1:]).

We then write one line to our log file consisting of the current date timestamp, two tab spaces, our message, and ending in a newline character:

    #------------------------------------------------------ 
def writeToLog(self, msg='', loglevel=LogLevel.DEBUG):
# control how much gets logged
if loglevel > self.loggingLevel:
return

# open log file in append mode
with open(self.log, mode='a', encoding='utf-8') as logFile:
msg = str(msg)
if msg.startswith(' '):
msg = msg[1:]
logFile.write(self.getDateTime() + ' ' + msg + ' ')

logFile.close()

We can now import our new Python module and, inside the __init__ section of our GUI code, can create an instance of the Logger class:

from os import path  
from Ch08_Code.Logger import Logger
class OOP():
def __init__(self):
# create Logger instance
fullPath = path.realpath(__file__)
self.log = Logger(fullPath)
print(self.log)

We are retrieving the full path to our running GUI script via path.realpath(__file__) and passing this into the initializer of the Logger class. If the logs folder does not exist, it will automatically be created by our Python code.

This creates the following results:

Callbacks_Refactored.py with print(self.log) uncommented

The preceding screenshot shows that we created an instance of our new Logger class and the following screenshot shows that both the logs folder as well as the log were created:

When we open up the log, we can see that the current date and time as well as a default string have been written into the log:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.38.92