pyutil.py 4.09 KB
# -*- coding: UTF-8 -*-

# @def Função para obter data e hora atual do sistema
# @param string Formato de data e hora
# @return string Retorna data e hora do sistema no momento da chamada
def getTimeStamp(dtFrmt='%Y-%m-%d_%H.%M.%S.%f'):
    from datetime import datetime
    if (dtFrmt == '%Y-%m-%d_%H.%M.%S.%f'):
        # [:-3] Remove 3 casas decimais dos milisegundos (ms)
        return datetime.now().strftime(dtFrmt)[:-3]
    else:
        return datetime.now().strftime(dtFrmt)

# @def Função para gravar log dos eventos em arquivo
# @param string Mensagem a ser salva
# @param int indice do tipo de log 1: Debug, 2: Info, 3: Warn, 4: Error, 5: Critical
# @param String Caminho completo do arquivo de logs
# @param String Formato de tempo utilizado
def log(logMsg="", logLevel=2, logFile="events.log", dtFrmt='%Y-%m-%d %H:%M:%S'):
    import logging

    logLevelArray = ["", "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL" ]
    logLevel %= len(logLevelArray)
    print("[%s] log %s: %s" % (getTimeStamp(), logLevelArray[logLevel], logMsg))

    #logFormat='[%(asctime)s.%(msecs).03d] %(levelname)s: <User: %(name)s> <Module: %(module)s> <Function: %(funcName)s>: %(message)s'
    logFormat='[%(asctime)s.%(msecs).03d] %(levelname)s: %(message)s'

    if (logLevel == 1):
        logging.basicConfig(filename=logFile, datefmt=dtFrmt, format=logFormat, level=logging.DEBUG)
        logging.Formatter(fmt='%(asctime)s',datefmt='%Y/%m/%d,%H:%M:%S.%f')
        logging.debug(logMsg)

    elif (logLevel == 2):
        logging.basicConfig(filename=logFile, datefmt=dtFrmt, format=logFormat, level=logging.INFO)
        logging.Formatter(fmt='%(asctime)s',datefmt='%Y/%m/%d,%H:%M:%S.%f')
        logging.info(logMsg)

    elif (logLevel == 3):
        logging.basicConfig(filename=logFile, datefmt=dtFrmt, format=logFormat, level=logging.WARN)
        logging.Formatter(fmt='%(asctime)s',datefmt='%Y/%m/%d,%H:%M:%S.%f')
        logging.warn(logMsg)

    elif (logLevel == 4):
        logging.basicConfig(filename=logFile, datefmt=dtFrmt, format=logFormat, level=logging.ERROR)
        logging.Formatter(fmt='%(asctime)s',datefmt='%Y/%m/%d,%H:%M:%S.%f')
        logging.error(logMsg)

    elif (logLevel == 5):
        logging.basicConfig(filename=logFile, datefmt=dtFrmt, format=logFormat, level=logging.CRITICAL)
        logging.Formatter(fmt='%(asctime)s',datefmt='%Y/%m/%d,%H:%M:%S.%f')
        logging.critical(logMsg)

def test_log():
    msg = " This is a message "
    log(msg + "Debug", 1)
    log(msg + "Info", 2)
    log(msg + "Warn", 3)
    log(msg + "Error", 4)
    log(msg + "Critical", 5)

# test_log()

# @def Função para exibir exceção
# @param string deve ser passado: "__file__" para identificar em qual arquivo ocorreu a exceção
# @return int Retorna 1
def printStackTrace(fromFile):
    from sys import exc_info
    from os.path import basename
    error = "\n    File name: %s\n    Function name: %s\n    Line code: %s\n    Type exception: %s\n    Message: %s" % (
            basename(fromFile), # basename(exc_info()[2].tb_frame.f_code.co_filename),
            exc_info()[2].tb_frame.f_code.co_name,
            exc_info()[2].tb_lineno,
            exc_info()[0].__name__,
            exc_info()[1]
    )
    log(error, 4)
    return 1

# @def Função que verifica se um arquivo existe
# @param string filePath: Caminho do arquivo a ser checado
# @return bool Verdadeiro se o arquivo existir, Falso caso contrário
def file_exists(filePath):
    from os.path import isfile, exists
    if ((isfile(filePath) == 1) and (exists(filePath) == 1)):
        return True
    else:
        return False

def file_rename(filename, fromfile):
    from shutil import move
    newFilename = ""
    isValidChar = True
    for char in reversed(filename):
        if (isValidChar == True):
            newFilename += char
        if (char == '_'):
            isValidChar = True
        elif (char == '.'):
            isValidChar = False
    if (len(filename) != len(newFilename)):
        try:
            move(filename, newFilename[::-1])
            return 1
        except Exception as e:
            printStackTrace(fromfile)
            return 0
    return 0