pyutil.py 3.59 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)
    log(msg + "Critical", 6)

# test_log()

def printStackTrace(filename):
    from sys import exc_info
    from os.path import basename
    print("\n[Exception begin]\n  File: %s\n  Name: %s\n  Line: %s\n  Type: %s\n  Message: %s\n[Exception end]\n" % (
            basename(filename), # 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],
        )
    )

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