當前位置: 首頁>>代碼示例>>Python>>正文


Python Logger.Logger類代碼示例

本文整理匯總了Python中pyaid.debug.Logger.Logger的典型用法代碼示例。如果您正苦於以下問題:Python Logger類的具體用法?Python Logger怎麽用?Python Logger使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Logger類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: getConfig

    def getConfig(cls, databaseUrl, writeCallback =None):
        logger = Logger(
            databaseUrl.replace(u'://', u'~').replace(u'/', u'--').replace(u'.vdb', u''),
            useStorageBuffer=True
        )
        if writeCallback is not None:
            logger.addWriteCallback(writeCallback)

        migrationPath = PyGlassModelUtils.getMigrationPathFromDatabaseUrl(databaseUrl)
        config = alembicConfig.Config(os.path.join(migrationPath, 'alembic.ini'), stdout=logger)

        config.set_main_option(
            'script_location',
            migrationPath
        )

        config.set_main_option(
            'sqlalchemy.url',
            PyGlassModelUtils.getEngineUrl(databaseUrl)
        )

        config.set_main_option(
            'url',
            PyGlassModelUtils.getEngineUrl(databaseUrl)
        )

        return config
開發者ID:hannahp,項目名稱:PyGlass,代碼行數:27,代碼來源:AlembicUtils.py

示例2: getConfig

    def getConfig(cls, databaseUrl, resourcesPath, localResourcesPath, writeCallback =None):
        """ Retrieves the Alembic configuration for the specified database URL stored within the
            resources and local resources path for the target application """

        logger = Logger(
            databaseUrl.replace('://', '~').replace('/', '--').replace('.vdb', ''),
            useStorageBuffer=True)

        if writeCallback is not None:
            logger.addWriteCallback(writeCallback)

        migrationPath = PyGlassModelUtils.getMigrationPathFromDatabaseUrl(
            databaseUrl, resourcesPath=resourcesPath)

        config = alembicConfig.Config(os.path.join(migrationPath, 'alembic.ini'), stdout=logger)

        engineUrl = PyGlassModelUtils.getEngineUrl(
            databaseUrl=databaseUrl, localResourcesPath=localResourcesPath)

        # These options are overridden during loading to prevent issues of absolute path corruption
        # when running in different deployment modes and when installed on different computers
        config.set_main_option('url', engineUrl)
        config.set_section_option('alembic', 'script_location', migrationPath)
        config.set_section_option('alembic', 'sqlalchemy.url', engineUrl)
        config.set_section_option('alembic', 'url', migrationPath)

        return config
開發者ID:sernst,項目名稱:PyGlass,代碼行數:27,代碼來源:AlembicUtils.py

示例3: runPythonExec

def runPythonExec(script, kwargs =None):
    from nimble.NimbleEnvironment import NimbleEnvironment
    from nimble.data.NimbleResponseData import NimbleResponseData
    from nimble.data.enum.DataKindEnum import DataKindEnum

    try:
        nimble.cmds.undoInfo(openChunk=True)
    except Exception as err:
        return False

    try:
        # Create a new, temporary module in which to run the script
        module = imp.new_module('runExecTempModule')

        # Initialize the script with script inputs
        setattr(module, NimbleEnvironment.REMOTE_KWARGS_KEY, kwargs if kwargs is not None else dict())
        setattr(module, NimbleEnvironment.REMOTE_RESULT_KEY, dict())

        # Executes the script in the new module
        exec_(script, module.__dict__)

        # Find a NimbleScriptBase derived class definition and if it exists, run it to populate the
        # results
        for name,value in Reflection.getReflectionDict(module).iteritems():
            if not inspect.isclass(value):
                continue

            if NimbleScriptBase in value.__bases__:
                getattr(module, name)().run()
                break

        # Retrieve the results object that contains all results set by the execution of the script
        result = getattr(module, NimbleEnvironment.REMOTE_RESULT_KEY)
    except Exception as err:
        logger = Logger('runPythonExec', printOut=True)
        logger.writeError('ERROR: Failed Remote Script Execution', err)
        result = NimbleResponseData(
            kind=DataKindEnum.PYTHON_SCRIPT,
            response=NimbleResponseData.FAILED_RESPONSE,
            error=str(err) )

    # If a result dictionary contains an error key format the response as a failure
    try:
        errorMessage = ArgsUtils.extract(
            NimbleEnvironment.REMOTE_RESULT_ERROR_KEY, None, result)
        if errorMessage:
            return NimbleResponseData(
                kind=DataKindEnum.PYTHON_SCRIPT,
                response=NimbleResponseData.FAILED_RESPONSE,
                error=errorMessage,
                payload=result)
    except Exception as err:
        pass

    try:
        nimble.cmds.undoInfo(closeChunk=True)
    except Exception as err:
        return False

    return result
開發者ID:sernst,項目名稱:Nimble,代碼行數:60,代碼來源:__init__.py

示例4: _getDetailedError

 def _getDetailedError(cls, message, error):
     return '\n'.join([
         Logger.logMessageToString(Logger.createLogMessage(
             logValue=Logger.createErrorMessage(message, error),
             traceStack=True,
             shaveStackTrace=0,
             htmlEscape=False)),
         'VERSION: {}'.format(sys.version) ])
開發者ID:sernst,項目名稱:Nimble,代碼行數:8,代碼來源:MayaRouter.py

示例5: SocketHandler

class SocketHandler(SocketServer.StreamRequestHandler):
    """A class for..."""

#===================================================================================================
#                                                                                       C L A S S

    SERVICE_UID   = 'test'
    VERBOSE       = False
    WORK_PATH     = '/var/lib/'
    RUN_PATH      = '/var/run/'
    LOG_PATH      = '/var/log/'

#___________________________________________________________________________________________________ __init__
    def __init__(self, request, client_address, server):
        self._log = Logger(self)
        self._log.write('Socket handler created')

        SocketServer.StreamRequestHandler.__init__(self, request, client_address, server)

#===================================================================================================
#                                                                                   G E T / S E T

#___________________________________________________________________________________________________ GS: returnResponse
    @property
    def returnResponse(self):
        return getattr(self.__class__, 'RETURN_RESPONSE', False)

#===================================================================================================
#                                                                                     P U B L I C

#___________________________________________________________________________________________________ handle
    def handle(self):
        try:
            data = self.rfile.readline().strip()
            self._log.write('HANDLE: ' + str(data))
            try:
                result = self._respondImpl(JSON.fromString(unquote(data)))
            except Exception as err:
                self._log.writeError('RESPOND FAILURE', err)
                if self.returnResponse:
                    self.wfile.write(JSON.asString({'error':1}))
                return

            if self.returnResponse:
                out = {'error':0}
                if result:
                    out['payload'] = result
                self.wfile.write(out)
        except Exception as err:
            self._log.write('HANDLE FAILURE', err)

        return

#===================================================================================================
#                                                                               P R O T E C T E D

#___________________________________________________________________________________________________ _respondImpl
    def _respondImpl(self, data):
        pass
開發者ID:sernst,項目名稱:PyAid,代碼行數:59,代碼來源:SocketHandler.py

示例6: __init__

 def __init__(self, logger =None):
     """Creates a new instance of TrackExporter."""
     self.results = None
     self.logger = logger
     self.modifications = 0
     if not logger:
         self.logger = Logger(self, printOut=True)
開發者ID:sernst,項目名稱:Cadence,代碼行數:7,代碼來源:TrackExporter.py

示例7: __init__

    def __init__(self, **kwargs):
        """Creates a new instance of MarkupError."""

        self._thrown     = Logger.getFormattedStackTrace(2, 3)
        self._definition = ArgsUtils.get('errorDef', None, kwargs)
        self._tag        = ArgsUtils.get('tag', None, kwargs)
        self._block      = ArgsUtils.get('block', self._tag.block if self._tag else None, kwargs)
        self._processor  = ArgsUtils.get('processor', self._tag.processor if self._tag else None, kwargs)
        self._code       = ArgsUtils.get('code', self._definition.code, kwargs, allowNone=False)
        self.label       = ArgsUtils.get('label', self._definition.label, kwargs, allowNone=False)
        self.message     = ArgsUtils.get('message', self._definition.message, kwargs, allowNone=False)
        self._critical   = ArgsUtils.get('critical', False, kwargs)

        replacements = ArgsUtils.getAsList('replacements', kwargs)
        replacements.append([u'#TAG#', unicode(self._tag.tagName if self._tag else u'???')])

        for r in replacements:
            if self.message:
                self.message = self.message.replace(unicode(r[0]), unicode(r[1]))

            if self.label:
                self.label = self.label.replace(unicode(r[0]), unicode(r[1]))

        self._verbose   = ArgsUtils.get('verbose', False, kwargs)
        self._line      = None
        self._character = None
        self._source    = None
        self._logSource = None
        self._populateData()
開發者ID:sernst,項目名稱:StaticFlow,代碼行數:29,代碼來源:MarkupError.py

示例8: __init__

    def __init__(self, parent, **kwargs):
        QtCore.QThread.__init__(self, parent)

        self._events           = dict()
        self._log              = Logger(self)
        self._log.trace        = True
        self._log.addPrintCallback(self._handleLogWritten)
        self._response         = None
        self._output           = None
        self._error            = None
        self._explicitComplete = ArgsUtils.get('explicitComplete', False, kwargs)

        class RETCompleteSignal(QtCore.QObject):
            signal = QtCore.Signal(dict)
        self._completeSignal = RETCompleteSignal()

        class RETLogSignal(QtCore.QObject):
            signal = QtCore.Signal(str)
        self._logSignal = RETLogSignal()

        class RETProgressSignal(QtCore.QObject):
            signal = QtCore.Signal(dict)
        self._progressSignal = RETProgressSignal()

        class RETEventSignal(QtCore.QObject):
            signal = QtCore.Signal(dict)
        self._eventSignal = RETEventSignal()

        # Add the thread to the static active thread storage so that it won't be garbage collected
        # until the thread completes.
        self.__class__._ACTIVE_THREAD_STORAGE.append(self)

        self._connectSignals(**kwargs)
開發者ID:hannahp,項目名稱:PyGlass,代碼行數:33,代碼來源:RemoteExecutionThread.py

示例9: __call__

    def __call__(self, *args, **kwargs):
        """Doc..."""
        if self.response is None:
            self.response = RemoteScriptResponse()
        if self.kwargs is None:
            self.kwargs = kwargs

        try:
            self.run()
        except Exception as err:
            message = "Nimble remote script run failure"
            NimbleEnvironment.logError(message, err)
            logMessage = Logger.createErrorMessage(message, err)
            self.putErrorResult(Logger.logMessageToString(logMessage=logMessage, includePrefix=False))
        result = self.response.result
        return result if result else dict()
開發者ID:sernst,項目名稱:Nimble,代碼行數:16,代碼來源:NimbleScriptBase.py

示例10: getLogger

    def getLogger(
            logIdentifier, kwargs =None, args =None, index =None, name ='logger', extract =False,
            trace =None
    ):
        if extract:
            res = ArgsUtils.extract(name, None, kwargs, args, index)
        else:
            res = ArgsUtils.get(name, None, kwargs, args, index)

        if res is None:
            from pyaid.debug.Logger import Logger
            res = Logger(logIdentifier)

        if trace is not None:
            res.trace = trace

        return res
開發者ID:hannahp,項目名稱:PyAid,代碼行數:17,代碼來源:ArgsUtils.py

示例11: __init__

    def __init__(
        self,
        targetPackageOrPath,
        rootPath,
        verbose=True,
        debug=False,
        trace=False,
        force=False,
        compress=False,
        buildOnly=False,
    ):
        """Creates a new instance of CoffeescriptBuilder."""

        self.buildOnly = buildOnly

        self._imports = dict()
        self._requires = dict()
        self._includes = dict()
        self._report = dict()
        self._warnings = []
        self._dependencyReport = dict()
        self._verbose = verbose
        self._log = Logger(self, printOut=True)
        self._trace = trace
        self._debug = debug
        self._targets = []
        self._force = force
        self._compress = compress
        self._rootPath = rootPath

        if not isinstance(targetPackageOrPath, CoffeescriptDependency):
            target = CoffeescriptDependency(targetPackageOrPath, rootPath, None)
        else:
            target = targetPackageOrPath

        if target.exists:
            self._targets.append(target)
        else:
            csFiles = CoffeescriptBuilder.getScriptsInPath(target.packagePath)

            # Look for exec matches first
            for f in csFiles:
                testTarget = CoffeescriptDependency(f, rootPath, None)
                if testTarget.isExec:
                    self._targets.append(testTarget)

            # Look for lib matches second. Lib matches are tested as a second pass because
            # constructing all exec files first potentially optimizes the import process for
            # the libraries.
            for f in csFiles:
                testTarget = CoffeescriptDependency(f, rootPath, None)
                if testTarget.isLib:
                    self._targets.append(testTarget)

        if len(self._targets) == 0:
            print("\n\n")
            self._log.write("No targets exist for: %s. Compilation aborted." % targetPackageOrPath)
            print("\n")
開發者ID:sernst,項目名稱:PyAid,代碼行數:58,代碼來源:CoffeescriptBuilder.py

示例12: run

    def run(self):
        """ Executes the analysis process, iterating through each of the analysis stages before
            cleaning up and exiting. """

        print('[OUTPUT PATH]: %s' % self.analysisRootPath)
        print(analysisStamp)
        print(tracksStamp)

        self._startTime = TimeUtils.getNowDatetime()

        myRootPath = self.getPath(isDir=True)
        if os.path.exists(myRootPath):
            FileUtils.emptyFolder(myRootPath)
        if not os.path.exists(myRootPath):
            os.makedirs(myRootPath)

        tempPath = self.tempPath
        if os.path.exists(tempPath):
            SystemUtils.remove(tempPath)
        os.makedirs(tempPath)

        if not self.logger.loggingPath:
            self.logger.loggingPath = myRootPath

        try:
            session = self.getAnalysisSession()
            self._preAnalyze()
            for stage in self._stages:
                self._currentStage = stage
                stage.analyze()
            self._currentStage = None
            self._postAnalyze()

            session.commit()
            session.close()
            self._success = True
        except Exception as err:
            session = self.getAnalysisSession()
            session.close()
            msg = [
                '[ERROR]: Failed to execute analysis',
                'STAGE: %s' % self._currentStage]
            self._errorMessage = Logger.createErrorMessage(msg, err)
            self.logger.writeError(msg, err)

        session = self.getTracksSession()
        session.close()

        self._cleanup()
        SystemUtils.remove(tempPath)

        self.logger.write('\n\n[%s]: %s (%s)' % (
            'SUCCESS' if self._success else 'FAILED',
            self.__class__.__name__,
            TimeUtils.toPrettyElapsedTime(self.elapsedTime)
        ), indent=False)
開發者ID:sernst,項目名稱:Cadence,代碼行數:56,代碼來源:AnalyzerBase.py

示例13: DataFormatConverter

class DataFormatConverter(object):
    """A class for converting between various data interchange formats, e.g. XML and JSON."""

#===================================================================================================
#                                                                                       C L A S S

#___________________________________________________________________________________________________ __init__
    def __init__(self):
        """Creates a new instance of ClassTemplate."""
        self._type = None
        self._src  = None
        self._log  = Logger('DataFormatConverter')
        self._path = None

#===================================================================================================
#                                                                                   G E T / S E T

#___________________________________________________________________________________________________ GS: propertyName
    @property
    def source(self):
        return self._src

#===================================================================================================
#                                                                                     P U B L I C

#___________________________________________________________________________________________________ load
    def load(self, path, fileType):
        if not os.path.exists(path):
            self._log.write('ERROR: Path does not exist [%s]. Unable to load.' % path)
            return False

        try:
            fh  = codecs.open(path, 'r', 'utf-8')
            res = fh.read()
            fh.close()
            enc = res.encode('utf-8')
            self.loads(enc, fileType)
        except Exception, err:
            self._log.writeError('Failed to load source file [%s].' % path, err)
            return False

        self._path = path
        return True
開發者ID:hannahp,項目名稱:PyAid,代碼行數:43,代碼來源:DataFormatConverter.py

示例14: IncludeCompressor

class IncludeCompressor(object):

#===================================================================================================
#                                                                                       C L A S S

    _REMOVE_COMMENT_RE      = re.compile('/\*.+\*/', re.DOTALL)
    _REMOVE_COMMENT_LINE_RE = re.compile('(^|\n)[\s\t]*//.+(\n|$)')

    JS_TYPE  = 'js'
    CSS_TYPE = 'css'

#___________________________________________________________________________________________________ __init__
    def __init__(self, compileCoffee =False):
        self._log           = Logger('IncludeCompressor')
        self._compileCoffee = compileCoffee

#===================================================================================================
#                                                                                     P U B L I C

#___________________________________________________________________________________________________ compress
    def compress(self, rootPath):
        if not self._fileExists(rootPath):
            return False
        elif os.path.isfile(rootPath):
            return self.compressFile(rootPath)
        else:
            return self.compressPath(rootPath)

#___________________________________________________________________________________________________ compressFile
    def compressFile(self, rootPath, directory =None):
        if not self._fileExists(rootPath):
            return False

        if self._compileCoffee:
            try:
                from pyaid.web.coffeescript.CoffeescriptBuilder import CoffeescriptBuilder
                CoffeescriptBuilder.compileAllOnPath(rootPath, os.path.dirname(rootPath), True)
                self._log.write('Coffeescript compiled.')
            except Exception, err:
                self._log.writeError('Failed to compile coffeescript file.', err)
                return False

        return self._compressFile(rootPath, directory)
開發者ID:hannahp,項目名稱:PyAid,代碼行數:43,代碼來源:IncludeCompressor.py

示例15: __init__

    def __init__(
        self,
        fileName,
        siteMap,
        labelTracks=True,
        labelColor="black",
        session=None,
        showUncertainty=True,
        showCenters=True,
        **kwargs
    ):
        """ Creates a new instance of CadenceDrawing.  Calls to the public functions line(), rect(),
            and others result in objects being added to the SVG canvas, with the file written by the
            save() method to specified fileName.  The second argument, the siteMap is provided as an
            argument to establish the correspondence between the Maya scene and the site siteMap
            coordinates. """

        self._logger = kwargs.get("logger")
        if not self._logger:
            self._logger = Logger(self, printOut=True)

        self.siteMapReady = siteMap.isReady
        if not self.siteMapReady:
            self._logger.write('[ERROR|CadenceDrawing]: Sitemap "%s-%s" not ready' % (siteMap.name, siteMap.level))
            return

        self.fileName = fileName
        self.siteMap = siteMap
        self.siteName = siteMap.name
        self.siteLevel = siteMap.level

        # Generally units can be specified in millimeters.  In a few cases, however, (e.g.,
        # PolyLine) the coordinates must be unqualified integers (as px).  The site maps, however
        # are in 'scaled mm'.  Hence the need for a cnversion factor pxPerMm. Unfortunately, the
        # conversion between px and mm is OS-dependent. The conversion from px to inches is 72 for
        # Apple but 90 more generally).

        ppi = 72 if OsUtils.isMac() else 90
        self.pxPerMm = ppi / 25.4

        # specify the width and height explicitly in mm, and likewise for the background rect
        left = siteMap.left * mm
        top = siteMap.top * mm
        width = siteMap.width * mm
        height = siteMap.height * mm

        self._drawing = svgwrite.Drawing(fileName, profile="tiny", size=(width, height), stroke=svgwrite.rgb(0, 0, 0))
        self._drawing.add(self._drawing.rect((left, top), (width, height), opacity="0"))

        self.groups = dict()

        if labelTracks:
            self.labelTracks(
                color=labelColor, session=session, showUncertainty=showUncertainty, showCenters=showCenters
            )
開發者ID:sernst,項目名稱:Cadence,代碼行數:55,代碼來源:CadenceDrawing.py


注:本文中的pyaid.debug.Logger.Logger類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。