The log file is important for the developer to debug, it also ensures that the user will not be distracted by program message.
Python provides module logging to help developers to complete the task conveniently, we can set customized format and different log levels for it. Developers can also turn it off to keep the world silent at any time.

Logging Levels:

 level function Numeric value NOTSET 0 DEBUG logging.debug() 10 INFO logging.info() 20 WARNING logging.warning() 30 ERROR logging.error() 40 CRITICAL logging.critical() 50

Here is a simple example which shows quickSort algorithm achieved by Python.

``````def quickSort(arr, low, high):
if low >= high:
return ;
left = low
right = high
tmp = arr[left]
while left < right:
while arr[right] >= tmp and right > left:
right = right - 1
if right > left:
arr[left], arr[right] = arr[right], arr[left]
left = left + 1
while arr[left] <= tmp and right > left:
left = left + 1
if right > left:
arr[left], arr[right] = arr[right], arr[left]
right = right - 1
quickSort( arr, low, left )
quickSort( arr, left+1, high )

arr = [5, 9, 19, 8, 7, 27]
n = len(arr)
quickSort(arr,0, n-1)
print ("Sorted array is:")
for i in range(n):
print ("%d" %arr[i]),``````

Output:

``````Sorted array is:
5 7 8 9 19 27``````

Add logging module to record the necessary information for the project.
We want to output the partial array after a sort in the quickSort algorithm to figure out what happened in the progress.

``````import logging

def quickSort(arr, low, high):
if low >= high:
logging.debug( arr[low:high+1] )
return ;
left = low
# ...
quickSort( arr, left+1, high )
logging.debug( arr[low:high+1] )

if __name__ == "__main__":
logging.basicConfig( filename="log.txt", level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s' )

arr = [5, 9, 19, 8, 7, 27]
#...``````

In addition, we want to truncate the log file in most cases.
After all, it’s disgusting to read too big file to explore the last scenario.

``````if __name__ == "__main__":
logging.basicConfig( filename="log.txt", level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s' )
#truncate the log.txt
with open( "log.txt", "w" ):
pass
# ...``````
Categories: Python

Article Rating
Subscribe
Notify of