def my_log():
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
handlers=[logging.FileHandler('message.log', 'a', 'utf-8')])
# ?????_?????__
_log = logging.getLogger('app.' + __name__)
host = '10.0.0.175'
port = 8080
# ??? 'xxxx' % (aa, bb)????????
_log.error('error to connect to %s:%d', host, port)
_log.addFilter(FilterFunc('foo')) # ?????foo()???????
lgg = logging.getLogger('app.network.client')
lgg.propagate = False # ??????
lgg.error('do you see me?') # ????????
lgg.setLevel(logging.CRITICAL)
lgg.error('now you see me?')
logging.disable(logging.DEBUG) # ????????
# ??log??????main?????????
config.fileConfig('applogcfg.ini')
python类fileConfig()的实例源码
def configure_logging(self):
logging_config_file = os.path.join(self.config_directory, 'logging.conf')
if os.path.isfile(logging_config_file):
config.fileConfig(logging_config_file)
else:
logging.basicConfig()
logging.captureWarnings(True)
def run():
parser = argparse.ArgumentParser()
parser.add_argument("service", help="Service to execute: 'api' or 'collector'", choices=["api", "collector"])
parser.add_argument("config_file", help="Config file path")
parser.add_argument("--logging", help="Logger configuration")
parser.add_argument("--port", help="API HTTP port (default is 8000)", default=8000)
parser.add_argument("--host", help="API hostname to listen on (default is 127.0.0.1)", default="127.0.0.1")
args = parser.parse_args()
config.read(args.config_file)
if args.logging:
print("Loading logger configuration from {0}".format(args.logging))
logging_config.fileConfig(args.logging, disable_existing_loggers=False)
else:
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
logging.debug("Logging to stdout")
if args.service == "api":
almanach_api = AlmanachApi()
almanach_api.run(host=args.host, port=args.port)
else:
almanach_collector = AlmanachCollector()
almanach_collector.run()
def load_configuration(config_file=DEFAULT_CONFIG_FILE):
"""
Loads logging configuration from the given configuration file.
:param config_file:
the configuration file (default=/etc/package/logging.conf)
:type config_file: str
"""
if not os.path.exists(config_file) or not os.path.isfile(config_file):
msg = '%s configuration file does not exist!', config_file
logging.getLogger(__name__).error(msg)
raise ValueError(msg)
try:
config.fileConfig(config_file, disable_existing_loggers=False)
logging.getLogger(__name__).info(
'%s configuration file was loaded.', config_file)
except Exception as e:
logging.getLogger(__name__).error(
'Failed to load configuration from %s!', config_file)
logging.getLogger(__name__).debug(str(e), exc_info=True)
raise e
def setup_logging():
"""Reads the Storj GUI logging configuration from logging.conf.
If the file does not exist it will load a default configuration.
Mac OS X (POSIX):
~/.storj-gui
Unix (POSIX):
~/.storj-gui
Win XP (not roaming):
``C:\Documents and Settings\<user>\Application Data\storj-gui``
Win 7 (not roaming):
``C:\\Users\<user>\AppData\Local\storj-gui``
"""
logging_conf = os.path.join(
click.get_app_dir(APP_NAME, force_posix=True),
'logging.conf')
if not os.path.exists(logging_conf) or not os.path.isfile(logging_conf):
load_default_logging()
logging.getLogger(__name__).warning('%s logging configuration file does not exist', logging_conf)
return
try:
config.fileConfig(logging_conf, disable_existing_loggers=False)
logging.getLogger(__name__).info('%s configuration file was loaded.', logging_conf)
except RuntimeError:
load_default_logging()
logging.getLogger(__name__).warning('failed to load configuration from %s', logging_conf)
return
logging.getLogger(__name__).info('using logging configuration from %s', logging_conf)
def configure_logging(self):
if isinstance(self.LOGGING, str):
config.fileConfig(self.LOGGING)
elif isinstance(self.LOGGING, dict):
config.dictConfig(self.LOGGING)
elif isinstance(self.LOGGING, type(None)):
# Disable all logging
if not _FORCE_PREVENT_LOGGING_DISABLE:
logging.disable(logging.CRITICAL)
else:
raise ConfigurationError('Invalid LOGGING: must be string, dict')
def _use_config_file(cls, config_file):
"""Use parsed logging configuration."""
try:
config.fileConfig(cls._PARSER, disable_existing_loggers=False)
LOG.info('Logging config file "%s" loaded successfully.',
config_file)
except OSError:
cls._catch_config_file_exception(config_file)
def add_program_config_arguments(cls, parser):
parser.add_argument(
"--cfg",
help="ARouteServer configuration file. "
"By default, the program looks for its configuration "
"file in the following paths: {}".format(
", ".join(program_config.DEFAULT_CFG_PATHS)),
metavar="FILE",
dest="cfg_program")
group = parser.add_argument_group(
title="Program configuration",
description="The following arguments override those provided "
"in the program's configuration file."
)
group.add_argument(
"--cache-dir",
help="Cache directory.",
metavar="DIR",
dest="cache_dir")
group.add_argument(
"--logging-config-file",
help="Logging configuration file, in Python fileConfig() format ("
"https://docs.python.org/2/library/logging.config.html"
"#configuration-file-format)",
dest="logging_config_file")
group.add_argument(
"--logging-level",
help="Logging level. Overrides any configuration given in the "
"logging configuration file.",
choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
dest="logging_level")