Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Logging tutorial!
#1
I just finished creating a logger class and thought it might be useful for some people as it's a module that can be re-used to add logging functionality to any project.

It's a simple class/bit of code really:

#!C:\Program Files\Python37\python.exe
import time
import os
from datetime import datetime, timezone

class Logger(object):
    logFile = "logFile.txt"
Note: replace 'logFile.txt' with whatever you named your logfile in the cwd.

Now, the following 2 mothods are required for our logger and will be used in the output of our other logger methods:

    @staticmethod
    def getErrorString(errLevel):
        return {0: "[SYS]",
                1: "[INFO]",
                2: "[WARN]",
                3: "[ERR]",
                4: "[CRITICAL]",
                }.get(errLevel, "[UNKNOWN]")

    @staticmethod
    def getTimeStamp():
        return str(time.strftime('%Y-%m-%d %H:%M:%S'))
Note, you can add any custom error levels you might want (ex. '5: "[FATAL]",).

Finally, we create our logger methods. You can make as many of these as you want, and use them to write to however many log files you need. You can either declare additional log files as objects in the class, or declare them in the methods themselves. Here's some example methods, writing to different log files:

    @staticmethod
    def writeAndPrintLine(text, errorLevel):
        message = Logger.getTimeStamp()+' '+Logger.getErrorString(errorLevel)+':\t'+text
        file = open(Logger.logFile, "a")
        file.write(message+'\n')
        file.close()
        print(message)

    @staticmethod    
    def recLog(text, errorLevel):
        message = Logger.getTimeStamp()+' '+Logger.getErrorString(errorLevel)+':\t'+text
        file = open("_recLog.txt", 'a')
        file.write(message+'\n')
        file.close()
        print(message)
So, here's our finished Logging class:

import time
import os
from datetime import datetime, timezone

class Logger(object):
    logFile = "logFile.txt"
    
    # writes to logFile.txt and prints to console
    @staticmethod
    def writeAndPrint(text, errorLevel):
        message = Logger.getTimeStamp()+' '+Logger.getErrorString(errorLevel)+':\t'+text
        file = open(Logger.logFile, "a")
        file.write(message+'\n')
        file.close()
        print(message)
      
     # writes to different log file, and prints to console  
    @staticmethod
    def logFile2(text, errorLevel):
        message = Logger.getTimeStamp()+' '+Logger.getErrorString(errorLevel)+':\t'+text
        f=open("_logfile2.txt", 'a')
        f.write(message+'\n')
        f.close()
        print(message)
        
    # prints to console, does not write to log file. 
    @staticmethod
    def printLine(text, errorLevel):
        message = Logger.getTimeStamp()+' '+Logger.getErrorString(errorLevel)+':\t'+text
        print(message)

    # method used for error level
    @staticmethod
    def getErrorString(errLevel):
        return {0: "[SYS]",
                1: "[INFO]",
                2: "[WARN]",
                3: "[ERR]",
                }.get(errLevel, "[UNKNOWN]")

    # method used for time stamp
    @staticmethod
    def getTimeStamp():
        return str(time.strftime('%Y-%m-%d %H:%M:%S'))
To use our logger in our programs/modules, call the class and method you want, followed by the string to log and the error level. Like this:

Logger.writeAndPrint('this message is logged in logFile.txt, error level 0!', 0)
Logger.logFile2('this message is logged in logFile2.txt, error level 3!', 3)
Logger.printLine('this message is just printed to console, err lvl 2!', 2)
And some example output:
[Image: g4j9end]
Reply
#2
just to mention the logging module from the standard library
and logging howto
and logging cookbook

No need to reinvent the wheel
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
lol very true!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020