pyNastran  0.5.0
pyNastran BDF Reader/Writer, OP2 Parser, and GUI
logger.py
Go to the documentation of this file.
00001 ## GNU Lesser General Public License
00002 ## 
00003 ## Program pyNastran - a python interface to NASTRAN files
00004 ## Copyright (C) 2011-2012  Steven Doyle, Al Danial
00005 ## 
00006 ## Authors and copyright holders of pyNastran
00007 ## Steven Doyle <mesheb82@gmail.com>
00008 ## Al Danial    <al.danial@gmail.com>
00009 ## 
00010 ## This file is part of pyNastran.
00011 ## 
00012 ## pyNastran is free software: you can redistribute it and/or modify
00013 ## it under the terms of the GNU Lesser General Public License as published by
00014 ## the Free Software Foundation, either version 3 of the License, or
00015 ## (at your option) any later version.
00016 ## 
00017 ## pyNastran is distributed in the hope that it will be useful,
00018 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
00019 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00020 ## GNU General Public License for more details.
00021 ## 
00022 ## You should have received a copy of the GNU Lesser General Public License
00023 ## along with pyNastran.  If not, see <http://www.gnu.org/licenses/>.
00024 ## 
00025 import os
00026 import sys
00027 import inspect
00028 import logging
00029 
00030 def frame(n):
00031     return inspect.currentframe(n+4) # jump 4 levels down to get out of the logger code
00032 
00033 def lineNum():
00034     return frame().f_lineno
00035 
00036 def fileNamE():
00037     return os.path.basename(frame().f_globals['__file__'])
00038 
00039 def fileNameLineNum(n=0):
00040     f = frame(n)
00041     lineNum = f.f_lineno
00042     fname = os.path.basename(f.f_globals['__file__'])
00043     return(fname,lineNum)
00044     
00045 class debugLogger(object):
00046     def __init__(self):
00047         pass
00048 
00049     #def frame(self): # good...
00050     #    return inspect.currentframe()
00051 
00052     def frame(self):
00053        #print help(inspect)
00054        return inspect.currentframe(4) # jump 4 levels down to get out of the logger code
00055 
00056     def lineno(self):
00057         """Returns the current line number in our program."""
00058         return self.frame().f_lineno
00059 
00060     def fname(self):
00061         """Returns the current file in our program."""
00062         return os.path.basename(self.frame().f_globals['__file__'])
00063 
00064     def funcName(self):
00065         """Returns the current function name in our program."""
00066         #print inspect.currentframe().f_back.f_back.f_locals['self']
00067         #print self.frame().f_globals.keys()
00068         #print self.frame().f_locals.keys()
00069 
00070         #return os.path.basename(self.frame().f_globals['__name__'])
00071         #return self.frame().__file__
00072         pass
00073 
00074     def properties(self):
00075         n = self.lineno()
00076         fname = self.fname()
00077         #funcName = self.funcName()
00078         funcName = ''
00079         return (n,fname,funcName)
00080 
00081     def fixMessage(self,msg,n=54):
00082         msg = str(msg)
00083         #print "msg = |%s| type=%s" %(msg,type(msg))
00084         lines = msg.split('\n')
00085         lines2 = [lines[0]]
00086 
00087         spaces = ' '*n
00088         #print "lines = ",lines
00089         for line in lines[1:]:
00090             lines2.append(spaces+line+'\n')
00091         msg2 = ''.join(lines2)
00092         return msg2
00093 
00094     def debug(self,msg):
00095         (n,fname,funcName) = self.properties()
00096         msg = self.fixMessage(msg)
00097         sys.stdout.write('DEBUG:   fname=%-25s lineNo=%-4s   %s\n' %(fname,n,msg))
00098 
00099     def info(self,msg):
00100         (n,fname,funcName) = self.properties()
00101         sys.stdout.write('INFO:    fname=%-25s lineNo=%-4s   %s\n' %(fname,n,msg))
00102 
00103     def warning(self,msg):
00104         (n,fname,funcName) = self.properties()
00105         sys.stdout.write('WARNING: fname=%-25s lineNo=%-4s   %s\n' %(fname,n,msg))
00106         #sys.stderr.write('WARNING: fname=%-25s lineNo=%-4s   %s\n' %(fname,n,msg))
00107 
00108     def error(self,msg):
00109         (n,fname,funcName) = self.properties()
00110         sys.stdout.write('ERROR:   fname=%-25s lineNo=%-4s   %s\n' %(fname,n,msg))
00111         #sys.stderr.write('ERROR:   fname=%-25s lineNo=%-4s   %s\n' %(fname,n,msg))
00112 
00113     def critical(self,msg):
00114         (n,fname,funcName) = self.properties()
00115         sys.stdout.write('CRITICAL fname=%-25s lineNo=%-4s   %s\n' %(fname,n,msg))
00116         #sys.stderr.write('CRITICAL fname=%-25s lineNo=%-4s   %s\n' %(fname,n,msg))
00117     ###
00118 
00119 class infoLogger(debugLogger):
00120     def debug(self,msg):
00121         pass
00122 
00123 class dummyLogger(object):
00124     def __init__(self):
00125         pass
00126 
00127     def startLog(self,level):
00128         if level=='debug':
00129             return debugLogger()
00130         elif level=='info':
00131             return infoLogger()
00132         else:
00133             raise RuntimeError("invalid logger:  debug, info ONLY!")
00134 
00135 def getLogger(log=None,level='debug'):
00136     """
00137     This function is useful as it will instantiate a dummy logger object if log=None
00138     log may be a logger object or None
00139     pyFile is the python file that the code was called from (unused)
00140     """
00141     if log==None:
00142         log = dummyLogger()
00143         logger = log.startLog(level)
00144     else:
00145         logger = log
00146     return logger
00147 
00148 def buildDummyLogger2(level='debug'):
00149     try:
00150         version = sys.version_info
00151         fname = 'pyNastran.py%s%s.log' %(version.major,version.minor)
00152         logPath = os.path.join(os.getcwd(),fname)
00153         if os.path.exists(logPath):
00154             os.remove(logPath)
00155 
00156         # create logger with 'pyNastran'
00157         logger = logging.getLogger('pyNastran')
00158         logger.setLevel(logging.DEBUG)
00159         # create file handler which logs even debug messages
00160         fh = logging.FileHandler(logPath)
00161         if level=='debug':
00162             fh.setLevel(logging.DEBUG)
00163         elif level=='info':
00164             fh.setLevel(logging.INFO)
00165         else:
00166             raise RuntimeError("invalid logger:  debug, info ONLY!")
00167         # create console handler with a higher log level
00168         ch = logging.StreamHandler()
00169         ch.setLevel(logging.ERROR)
00170         # create formatter and add it to the handlers
00171         formatter = logging.Formatter('%(levelname)-8s:  %(filename)-25s linenum=%(lineno)-4s %(message)s')
00172         fh.setFormatter(formatter)
00173         ch.setFormatter(formatter)
00174         # add the handlers to the logger
00175         logger.addHandler(fh)
00176         logger.addHandler(ch)
00177 
00178         logger.info('logger is initialized---')
00179     except:
00180         logger = logging.getLogger('pyNastran')
00181 
00182     return logger
00183 
00184 if __name__=='__main__':
00185     # how to use a dummy logger
00186     logger = dummyLogger()
00187     log = logger.startLog('debug') # or info
00188     log.debug('test message')
00189     log.warning('asf')
00190     
00191 
 All Classes Namespaces Files Functions Variables