Package ivs :: Package aux :: Module loggers
[hide private]
[frames] | no frames]

Source Code for Module ivs.aux.loggers

 1  # -*- coding: utf-8 -*- 
 2  """ 
 3  Set up and configure basic logging facilities. 
 4   
 5  Typcical use: import the module, and call 
 6   
 7  >>> logger = get_basic_logger() 
 8   
 9  in your script. All relevant messages will get logged to the terminal. 
10  """ 
11  import logging 
12   
13 -class NullHandler(logging.Handler):
14 """ 15 The NullHandler is part of the standard logging module only from Python 2.7 on. 16 """ 17 level = 100
18 - def emit(self, record):
19 pass
20
21 -def get_basic_logger(name="",clevel='INFO', 22 flevel='DEBUG',filename=None,filemode='w'):
23 """ 24 Return a basic logger via a log file and/or terminal. 25 26 Example 1: log only to the console, accepting levels "INFO" and above 27 28 >>> logger = loggers.get_basic_logger() 29 30 Example 2: log only to the console, accepting levels "DEBUG" and above 31 32 >>> logger = loggers.get_basic_logger(clevel='DEBUG') 33 34 Example 3: log only to a file, accepting levels "DEBUG" and above 35 36 >>> logger = loggers.get_basic_logger(clevel=None,filename='mylog.log') 37 38 Example 4: log only to a file, accepting levels "INFO" and above 39 40 >>> logger = loggers.get_basic_logger(clevel=None,flevel='INFO',filename='mylog.log') 41 42 Example 5: log to the terminal (INFO and above) and file (DEBUG and above) 43 44 >>> logger = loggers.get_basic_logger(filename='mylog.log') 45 46 @param name: name of the logger 47 @type name: str 48 """ 49 #-- define formats 50 format = '%(asctime)s %(name)s %(levelname)-8s %(message)s' 51 datefmt = '%a, %d %b %Y %H:%M' 52 53 if clevel: clevel = logging.__dict__[clevel.upper()] 54 if flevel: flevel = logging.__dict__[flevel.upper()] 55 56 #-- set up basic configuration. 57 # The basicConfig sets up one default logger. If you give a filename, it's 58 # a FileHandler, otherwise a StreamHandler. 59 #-- If we want console and filename, first set up a basic FileHandler, then 60 # add terminal StreamHandler 61 if filename is not None: 62 logging.basicConfig(level=min(flevel,clevel), 63 format=format,datefmt=datefmt, 64 filename=filename,filemode=filemode) 65 if filename is not None and clevel: 66 # define a Handler which writes INFO messages or higher to the sys.stderr 67 ch = logging.StreamHandler() 68 ch.setLevel(clevel) 69 # set a format which is simpler for console use 70 formatter = logging.Formatter(format,datefmt) 71 # tell the handler to use this format 72 ch.setFormatter(formatter) 73 logging.getLogger(name).addHandler(ch) 74 #-- If we only want a console: 75 else: 76 logging.basicConfig(level=clevel,format=format,datefmt=datefmt,filename=filename,filemode=filemode) 77 return logging.getLogger(name)
78