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

import datetime
import logging
import os
import shutil
import sys

# @def funcao 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(date_fmt="%Y-%m-%d %H:%M:%S.%f"):
    if ("%f" in date_fmt):
        # [:-3] remove 3 casas decimais dos milisegundos (ms)
        return datetime.datetime.now().strftime(date_fmt)[:-3]
    else:
        return datetime.datetime.now().strftime(date_fmt)

# @def funcao para gravar log dos eventos em arquivo
# @param string mensagem a ser salva
# @param int indice do tipo de log 0: apenas print, 1: debug, 2: info, 3: warn, 4: error, 5: critical
# @param string caminho completo do arquivo de logs
# @param string formato de tempo utilizado
# @return none
def log(msg="", log_level=2, log_file="events.log"):
    dict_level = {
        0: ["Print", None, None],
        1: ["DEBUG", logging.DEBUG, logging.debug],
        2: ["INFO", logging.INFO, logging.info],
        3: ["WARNING", logging.WARN, logging.warn],
        4: ["ERROR", logging.ERROR, logging.error],
        5: ["CRITICAL", logging.CRITICAL, logging.critical]
    }
    # log_format = "[%(asctime)s.%(msecs).03d] %(levelname)s: <User: %(name)s> <Module: %(module)s> <Function: %(funcName)s>: %(message)s"
    log_format = "[%(asctime)s.%(msecs).03d] %(levelname)s: %(message)s"
    date_fmt = "%Y-%m-%d %H:%M:%S"
    logging.basicConfig(filename=log_file, datefmt=date_fmt, format=log_format, level=dict_level[log_level][1])
    logging.Formatter(fmt="%(asctime)s", datefmt=date_fmt)
    log_level %= len(dict_level)
    write_mode = dict_level[log_level][2]
    print("[%s] %s: %s" % (getTimeStamp(), dict_level[log_level][0], msg))
    if (write_mode != None):
        write_mode(msg)
    return

# @def funcao para exibir excecao
# @param string deve ser passado: "__file__" para identificar em qual modulo ocorreu a excecao
# @return int retorna 1
def print_stack_trace():
    error = "\n    File name: %s\n    Function name: %s\n    Line code: %s\n    Type exception: %s\n    Message: %s" % (
            os.path.basename(sys.exc_info()[2].tb_frame.f_code.co_filename),
            sys.exc_info()[2].tb_frame.f_code.co_name,
            sys.exc_info()[2].tb_lineno,
            sys.exc_info()[0].__name__,
            sys.exc_info()[1]
    )
    log(error, 4)
    return 1

def get_date_now():
    return datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S')

def is_int(string):
    try:
        int(string)
        return True
    except ValueError:
        return False