import sys
import appconfig as config

if config.env == config.ENTERPRISE:
    from com.orangescape.logging import WSGILogger
    default_logger = WSGILogger.getLogger()
else:
    default_logger= __import__('logging')

def getLogger(script_name=None):
    if script_name is not None and (config.env == config.ENTERPRISE):
        return WSGILogger.getLogger(script_name)
    else:
        return default_logger

def logStackTrace(logger):
    #Pass logger to the method, so that the stack trace would have prefix showing in which module error is thrown
    if logger is None:
        logger=default_logger
    logger.error(''.join([formatLine(traceInfo) for traceInfo in StackTraceFromCurrentException()]))

def formatLine(lineInfo):
    fileName, lineNo, name = lineInfo
    return '\nFile "%s", line %s, in %s' % (fileName, lineNo, name)

def StackTraceFromCurrentException():
    traceback = sys.exc_info()[2]
    stackTrace = []
    while traceback is not None:
        frame = traceback.tb_frame
        lineno = traceback.tb_lineno
        code = frame.f_code
        filename = code.co_filename
        name = code.co_name
        stackTrace.append((filename, lineno, name))
        traceback = traceback.tb_next
    sys.exc_clear()
    return stackTrace