def setup_logging(handlers, facility, level):
global log
log = logging.getLogger('export-trac')
formatter = logging.Formatter(' | '.join(['%(asctime)s', '%(name)s', '%(levelname)s', '%(message)s']))
if handlers in ['syslog', 'both']:
sh = logging.handlers.SysLogHandler(address='/dev/log', facility=facility)
sh.setFormatter(formatter)
log.addHandler(sh)
if handlers in ['stdout', 'both']:
ch = logging.StreamHandler()
ch.setFormatter(formatter)
log.addHandler(ch)
lmap = {
'CRITICAL': logging.CRITICAL,
'ERROR': logging.ERROR,
'WARNING': logging.WARNING,
'INFO': logging.INFO,
'DEBUG': logging.DEBUG,
'NOTSET': logging.NOTSET
}
log.setLevel(lmap[level])
python类NOTSET的实例源码
def __init__(
self, nameparts,
propagate=False,
level=logging.NOTSET,
log_dir=None,
*args, **kwargs
):
super(BaseLogger, self).__init__()
self._nameparts = nameparts
self._propagate = None
self._level = None
self._log_dir = None
self._name = ''.join(map(str, nameparts.values()))
self.logger = logging.getLogger(self._name)
self.propagate = propagate
self.level = level
self.log_dir = log_dir
def log(self, level, msg, *args, **kwargs):
"""Delegate a log call to the underlying logger.
The level here is determined by the echo
flag as well as that of the underlying logger, and
logger._log() is called directly.
"""
# inline the logic from isEnabledFor(),
# getEffectiveLevel(), to avoid overhead.
if self.logger.manager.disable >= level:
return
selected_level = self._echo_map[self.echo]
if selected_level == logging.NOTSET:
selected_level = self.logger.getEffectiveLevel()
if level >= selected_level:
self.logger._log(level, msg, args, **kwargs)
def log(self, level, msg, *args, **kwargs):
"""Delegate a log call to the underlying logger.
The level here is determined by the echo
flag as well as that of the underlying logger, and
logger._log() is called directly.
"""
# inline the logic from isEnabledFor(),
# getEffectiveLevel(), to avoid overhead.
if self.logger.manager.disable >= level:
return
selected_level = self._echo_map[self.echo]
if selected_level == logging.NOTSET:
selected_level = self.logger.getEffectiveLevel()
if level >= selected_level:
self.logger._log(level, msg, args, **kwargs)
def log(self, level, msg, *args, **kwargs):
"""Delegate a log call to the underlying logger.
The level here is determined by the echo
flag as well as that of the underlying logger, and
logger._log() is called directly.
"""
# inline the logic from isEnabledFor(),
# getEffectiveLevel(), to avoid overhead.
if self.logger.manager.disable >= level:
return
selected_level = self._echo_map[self.echo]
if selected_level == logging.NOTSET:
selected_level = self.logger.getEffectiveLevel()
if level >= selected_level:
self.logger._log(level, msg, args, **kwargs)
def setup_logging(opts):
logging.root.addHandler(logging.NullHandler())
if opts.verbose:
logging_levels = {
0:logging.CRITICAL,
1:logging.ERROR,
2:logging.WARNING,
3:logging.INFO,
4:logging.DEBUG,
5:logging.NOTSET
}
fmt = '%(asctime)-15s.%(msecs)03d [%(threadName)10.10s] [%(levelname)6.6s] %(name)s#%(funcName)s:%(lineno)s %(message)s'
datefmt = '%Y-%m-%dT%H:%M:%S'
formatter = logging.Formatter(fmt, datefmt=datefmt)
formatter.converter = time.gmtime
hnd = logging.StreamHandler(stream=sys.stdout)
hnd.setFormatter(formatter)
logging.root.addHandler(hnd)
logging.root.setLevel(logging_levels[opts.verbose - 1])
def __init__(self, level=logging.NOTSET, host=mongo_server, port=27017, database_name='logs', collection='logs',
username=None, password=None, fail_silently=False, formatter=None):
"""Setting up mongo handler, initializing mongo database connection via pymongo."""
logging.Handler.__init__(self, level)
self.host = host
self.port = port
self.database_name = database_name
self.collection_name = collection
self.username = username
self.password = password
self.fail_silently = fail_silently
self.connection = None
self.db = None
self.collection = None
self.authenticated = False
self.formatter = formatter or MongoFormatter()
self._connect()
def _handle_existing_loggers(existing, child_loggers, disable_existing):
"""
When (re)configuring logging, handle loggers which were in the previous
configuration but are not in the new configuration. There's no point
deleting them as other threads may continue to hold references to them;
and by disabling them, you stop them doing any logging.
However, don't disable children of named loggers, as that's probably not
what was intended by the user. Also, allow existing loggers to NOT be
disabled if disable_existing is false.
"""
root = logging.root
for log in existing:
logger = root.manager.loggerDict[log]
if log in child_loggers:
logger.level = logging.NOTSET
logger.handlers = []
logger.propagate = True
else:
logger.disabled = disable_existing
def init_logger(self, log_type, path):
"""
:param path: Where log file will be created
:param log_type: Type of log to recording. Example logging.NOTSET
"""
self.__log_file_path = os.path.join(path, self.__log_filename)
log_formatter = logging.Formatter(
"%(asctime)s [%(levelname)-8.8s] %(message)s")
self.__logger = logging.getLogger()
file_handler = SizedTimedRotatingFileHandler(
self.__log_file_path,
max_bytes=1000000,
backup_count=5,
interval=24,
# encoding='bz2',
# uncomment for bz2 compression
)
file_handler.setFormatter(log_formatter)
self.__logger.addHandler(file_handler)
console_handler = logging.StreamHandler()
console_handler.setFormatter(log_formatter)
self.__logger.addHandler(console_handler)
self.__logger.setLevel(log_type)
def saveLoggingContext(self, logcfg_url, oldstyle_loglevel, rscCtx ):
# apply resource context to macro definitions
if rscCtx:
rscCtx.apply(self.loggingMacros )
self.loggingCtx = rscCtx
# test we have a logging URLx
self.loggingURL = logcfg_url
if logcfg_url==None or logcfg_url=="" :
self.logConfig = ossie.logger.GetDefaultConfig()
else:
# try to process URL and grab contents
try:
cfg_data=ossie.logger.GetConfigFileContents( logcfg_url )
if cfg_data and len(cfg_data) > 0 :
self.logConfig = ossie.logger.ExpandMacros( cfg_data, self.loggingMacros )
except:
pass
# apply logging level if explicitly stated
if oldstyle_loglevel != None and oldstyle_loglevel > -1 :
loglevel = ossie.logger.ConvertLogLevel(oldstyle_loglevel)
self.setLogLevel( "", loglevel )
if self._log and self._log.getEffectiveLevel() == logging.NOTSET:
self.setLevel( self._logid, loglevel )
else:
if self._log and self._log.getEffectiveLevel() == logging.NOTSET:
loglevel = ossie.logger.ConvertLog4ToCFLevel( logging.getLogger(None).getEffectiveLevel() )
self.setLogLevel( self._logid, loglevel )
# assign an event channel manager to the logging library
ossie.logger.SetEventChannelManager( self._ecm )
def __init__(self):
self.stream = sys.stdout # in log4j stdout is default
self.threshold = logging.NOTSET
self.log4pyProps = {'strm':sys.stdout}
def __init__(self):
self.threshold = logging.NOTSET
self.log4pyProps = {}
def __init__(self):
self.threshold = logging.NOTSET
self.log4pyProps = {}
def __init__(self):
self.threshold = logging.NOTSET
self.log4pyProps = {}
def setUp(self):
self.setContext()
if self.srcData:
self.seq = self.srcData
else:
self.seq = range(100)
self.orb = CORBA.ORB_init();
self.rootPOA = self.orb.resolve_initial_references("RootPOA")
self.logger = logging.getLogger(self.ptype[0])
self.logger.setLevel(logging.NOTSET)
self.logger.info( "Setup - Multiout Create Ports Table " );
self.ip1 = bulkio.InFloatPort("sink_1", self.logger );
self.ip1_oid = self.rootPOA.activate_object(self.ip1);
self.ip2 = bulkio.InFloatPort("sink_2", self.logger );
self.ip2_oid = self.rootPOA.activate_object(self.ip2);
self.ip3 = bulkio.InFloatPort("sink_3", self.logger );
self.ip3_oid = self.rootPOA.activate_object(self.ip3);
self.ip4 = bulkio.InFloatPort("sink_4", self.logger );
self.ip4_oid = self.rootPOA.activate_object(self.ip4);
self.port = bulkio.OutFloatPort("multiout_source", self.logger );
self.port_oid = self.rootPOA.activate_object(self.port);
self.desc_list=[];
self.logger.info( "Setup - Multiout Connection Table " );
self.desc_list.append( bulkio.connection_descriptor_struct( port_name="multiout_source", connection_id="connection_1", stream_id="stream-1-1" ) )
self.desc_list.append( bulkio.connection_descriptor_struct( port_name="multiout_source", connection_id="connection_1", stream_id="stream-1-2" ) )
self.desc_list.append( bulkio.connection_descriptor_struct( port_name="multiout_source", connection_id="connection_1", stream_id="stream-1-3" ) )
self.desc_list.append( bulkio.connection_descriptor_struct( port_name="multiout_source", connection_id="connection_2", stream_id="stream-2-1" ) )
self.desc_list.append( bulkio.connection_descriptor_struct( port_name="multiout_source", connection_id="connection_2", stream_id="stream-2-2" ) )
self.desc_list.append( bulkio.connection_descriptor_struct( port_name="multiout_source", connection_id="connection_2", stream_id="stream-2-3" ) )
self.desc_list.append( bulkio.connection_descriptor_struct( port_name="multiout_source", connection_id="connection_3", stream_id="stream-3-1" ) )
self.desc_list.append( bulkio.connection_descriptor_struct( port_name="multiout_source", connection_id="connection_3", stream_id="stream-3-2" ) )
self.desc_list.append( bulkio.connection_descriptor_struct( port_name="multiout_source", connection_id="connection_3", stream_id="stream-3-3" ) )
self.desc_list.append( bulkio.connection_descriptor_struct( port_name="multiout_source", connection_id="connection_4", stream_id="stream-4-1" ) )
def setUp(self):
self.setContext()
if self.srcData:
self.seq = self.srcData
else:
self.seq = range(100)
self.orb = CORBA.ORB_init();
self.rootPOA = self.orb.resolve_initial_references("RootPOA")
self.logger = logging.getLogger(self.ptype[0])
self.logger.setLevel(logging.NOTSET)
self.logger.info( "Setup - Multiout Create Ports Table " );
self.ip1 = bulkio.InFloatPort("sink_1", self.logger );
self.ip1_oid = self.rootPOA.activate_object(self.ip1);
self.ip2 = bulkio.InFloatPort("sink_2", self.logger );
self.ip2_oid = self.rootPOA.activate_object(self.ip2);
self.ip3 = bulkio.InFloatPort("sink_3", self.logger );
self.ip3_oid = self.rootPOA.activate_object(self.ip3);
self.ip4 = bulkio.InFloatPort("sink_4", self.logger );
self.ip4_oid = self.rootPOA.activate_object(self.ip4);
self.port = bulkio.OutFloatPort("multiout_source", self.logger );
self.port_oid = self.rootPOA.activate_object(self.port);
self.desc_list=[];
self.logger.info( "Setup - Multiout Connection Table " );
self.desc_list.append( bulkio.connection_descriptor_struct( port_name="multiout_source", connection_id="connection_1", stream_id="stream-1-1" ) )
self.desc_list.append( bulkio.connection_descriptor_struct( port_name="multiout_source", connection_id="connection_1", stream_id="stream-1-2" ) )
self.desc_list.append( bulkio.connection_descriptor_struct( port_name="multiout_source", connection_id="connection_1", stream_id="stream-1-3" ) )
self.desc_list.append( bulkio.connection_descriptor_struct( port_name="multiout_source", connection_id="connection_2", stream_id="stream-2-1" ) )
self.desc_list.append( bulkio.connection_descriptor_struct( port_name="multiout_source", connection_id="connection_2", stream_id="stream-2-2" ) )
self.desc_list.append( bulkio.connection_descriptor_struct( port_name="multiout_source", connection_id="connection_2", stream_id="stream-2-3" ) )
self.desc_list.append( bulkio.connection_descriptor_struct( port_name="multiout_source", connection_id="connection_3", stream_id="stream-3-1" ) )
self.desc_list.append( bulkio.connection_descriptor_struct( port_name="multiout_source", connection_id="connection_3", stream_id="stream-3-2" ) )
self.desc_list.append( bulkio.connection_descriptor_struct( port_name="multiout_source", connection_id="connection_3", stream_id="stream-3-3" ) )
self.desc_list.append( bulkio.connection_descriptor_struct( port_name="multiout_source", connection_id="connection_4", stream_id="stream-4-1" ) )
def _resetExistingLoggers(parent="root"):
""" Reset the logger named 'parent' and all its children to their initial
state, if they already exist in the current configuration.
"""
root = logging.root
# get sorted list of all existing loggers
existing = sorted(root.manager.loggerDict.keys())
if parent == "root":
# all the existing loggers are children of 'root'
loggers_to_reset = [parent] + existing
elif parent not in existing:
# nothing to do
return
elif parent in existing:
loggers_to_reset = [parent]
# collect children, starting with the entry after parent name
i = existing.index(parent) + 1
prefixed = parent + "."
pflen = len(prefixed)
num_existing = len(existing)
while i < num_existing:
if existing[i][:pflen] == prefixed:
loggers_to_reset.append(existing[i])
i += 1
for name in loggers_to_reset:
if name == "root":
root.setLevel(logging.WARNING)
for h in root.handlers[:]:
root.removeHandler(h)
for f in root.filters[:]:
root.removeFilters(f)
root.disabled = False
else:
logger = root.manager.loggerDict[name]
logger.level = logging.NOTSET
logger.handlers = []
logger.filters = []
logger.propagate = True
logger.disabled = False
def __init__(self, level=logging.NOTSET):
"""
Initialize the handler.
"""
logging.Handler.__init__(self, level)
def __init__(self,
name=None,
router=None,
load_env=True,
log_config=LOGGING):
if log_config:
logging.config.dictConfig(log_config)
# Only set up a default log handler if the
# end-user application didn't set anything up.
if not (logging.root.handlers and
log.level == logging.NOTSET and
log_config):
formatter = logging.Formatter(
"%(asctime)s: %(levelname)s: %(message)s")
handler = logging.StreamHandler()
handler.setFormatter(formatter)
log.addHandler(handler)
log.setLevel(logging.INFO)
# Get name from previous stack frame
if name is None:
frame_records = stack()[1]
name = getmodulename(frame_records[1])
self.name = name
self.config = Config(load_env=load_env)
self.router = router or PathRouter()
self.debug = None
self.static_handler = None
def getEffectiveLevel(self):
"""What's the effective level for this logger?"""
level = self._echo_map[self.echo]
if level == logging.NOTSET:
level = self.logger.getEffectiveLevel()
return level