Python django.conf.settings.LOGGING Examples

The following are 22 code examples for showing how to use django.conf.settings.LOGGING(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .

Example 1
Project: bioforum   Author: reBiocoder   File: __init__.py    License: MIT License 6 votes vote down vote up
def setup(set_prefix=True):
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    Set the thread-local urlresolvers script prefix if `set_prefix` is True.
    """
    from django.apps import apps
    from django.conf import settings
    from django.urls import set_script_prefix
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    if set_prefix:
        set_script_prefix(
            '/' if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME
        )
    apps.populate(settings.INSTALLED_APPS) 
Example 2
Project: lexpredict-contraxsuite   Author: LexPredict   File: decorators.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get_string_db_logger():
    """
    Gets you what you need to log to a string. Returns a pair of StringIO, logger variables.
    >>> output, logger = get_string_db_logger()
    >>> call_stuff_to_debug_with_logger(logger=logger)
    >>> print output.getvalue()
    """
    logger = logging.getLogger('django.db.backends')
    logger.setLevel(logging.DEBUG)
    try:
        fmt = settings.LOGGING['formatters']['verbose']['format']
    except KeyError:
        fmt = "%(levelname)-7s %(asctime)s | %(message)s"
    formatter = logging.Formatter(fmt)
    output = StringIO()
    string_handler = logging.StreamHandler(output)
    string_handler.setFormatter(formatter)
    string_handler.setLevel(logging.DEBUG)
    logger.addHandler(string_handler)

    return output, logger 
Example 3
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: __init__.py    License: MIT License 6 votes vote down vote up
def setup(set_prefix=True):
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    Set the thread-local urlresolvers script prefix if `set_prefix` is True.
    """
    from django.apps import apps
    from django.conf import settings
    from django.urls import set_script_prefix
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    if set_prefix:
        set_script_prefix(
            '/' if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME
        )
    apps.populate(settings.INSTALLED_APPS) 
Example 4
Project: python   Author: Yeah-Kun   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def setup(set_prefix=True):
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    Set the thread-local urlresolvers script prefix if `set_prefix` is True.
    """
    from django.apps import apps
    from django.conf import settings
    from django.urls import set_script_prefix
    from django.utils.encoding import force_text
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    if set_prefix:
        set_script_prefix(
            '/' if settings.FORCE_SCRIPT_NAME is None else force_text(settings.FORCE_SCRIPT_NAME)
        )
    apps.populate(settings.INSTALLED_APPS) 
Example 5
Project: python2017   Author: bpgc-cte   File: __init__.py    License: MIT License 6 votes vote down vote up
def setup(set_prefix=True):
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    Set the thread-local urlresolvers script prefix if `set_prefix` is True.
    """
    from django.apps import apps
    from django.conf import settings
    from django.urls import set_script_prefix
    from django.utils.encoding import force_text
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    if set_prefix:
        set_script_prefix(
            '/' if settings.FORCE_SCRIPT_NAME is None else force_text(settings.FORCE_SCRIPT_NAME)
        )
    apps.populate(settings.INSTALLED_APPS) 
Example 6
Project: hawthorne   Author: indietyp   File: report.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
    with Mainframe() as mainframe:
      uname = platform.uname()
      with open(settings.LOGGING['handlers']['file']['filename'], 'r') as log:
        traceback = self.tail(log, 100)

      payload = {
          'path': sys.path,
          'version': platform.python_version(),
          'system': {x: uname.__getattribute__(x) for x in uname._fields},
          'distro': '-'.join(platform.linux_distribution()),
          'log': traceback,
          'directory': settings.BASE_DIR
      }
      response = requests.put("https://{}/api/v1/instance/{}/report".format(
                              settings.MAINFRAME, mainframe().id),
                              json=payload)

      identifier = response.json()['result']['id']

      self.stdout.write(self.style.SUCCESS("""
        When talking to the maintainer indietyp,
        please use this ID to identify your ticket:"""))
      self.stdout.write(identifier) 
Example 7
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def setUp(self):
        logging_conf = """
[loggers]
keys=root
[handlers]
keys=stream
[formatters]
keys=simple
[logger_root]
handlers=stream
[handler_stream]
class=StreamHandler
formatter=simple
args=(sys.stdout,)
[formatter_simple]
format=%(message)s
"""
        self.temp_file = NamedTemporaryFile()
        self.temp_file.write(logging_conf.encode())
        self.temp_file.flush()
        sdict = {'LOGGING_CONFIG': '"logging.config.fileConfig"',
                 'LOGGING': 'r"%s"' % self.temp_file.name}
        self.write_settings('settings.py', sdict=sdict) 
Example 8
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def setup():
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    """
    from django.apps import apps
    from django.conf import settings
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    apps.populate(settings.INSTALLED_APPS) 
Example 9
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def setup():
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    """
    from django.apps import apps
    from django.conf import settings
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    apps.populate(settings.INSTALLED_APPS) 
Example 10
Project: dingtalk-django-example   Author: 007gzs   File: celery.py    License: GNU General Public License v3.0 5 votes vote down vote up
def configure_logger(conf=None, **kwargs):
    from django.conf import settings
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 
Example 11
Project: meeting   Author: 007gzs   File: celery.py    License: GNU General Public License v3.0 5 votes vote down vote up
def configure_logger(conf=None, **kwargs):
    from django.conf import settings
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 
Example 12
Project: oh-my-rss   Author: richshaw2015   File: views_dash.py    License: MIT License 5 votes vote down vote up
def get_warn_log(request):
    warn_log_file = settings.LOGGING['handlers']['my_warn']['filename']
    logs = list(reversed(open(warn_log_file).read().split('\n')))[:500]

    logs = [l for l in logs if l]

    context = dict()
    context['logs'] = logs

    return render(request, 'dashboard/logs.html', context=context) 
Example 13
Project: ansible-openwisp2   Author: openwisp   File: celery.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def config_loggers(*args, **kwargs):
    dictConfig(settings.LOGGING) 
Example 14
Project: openhgsenti   Author: drexly   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def setup():
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    """
    from django.apps import apps
    from django.conf import settings
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    apps.populate(settings.INSTALLED_APPS) 
Example 15
Project: ChRIS_ultron_backEnd   Author: FNNDSC   File: celery.py    License: MIT License 5 votes vote down vote up
def config_loggers(*args, **kwags):
    dictConfig(settings.LOGGING)

# example task that is passed info about itself 
Example 16
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def setUpClass(cls):
        super().setUpClass()
        cls._logging = settings.LOGGING
        logging.config.dictConfig(DEFAULT_LOGGING) 
Example 17
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        log_config = """{
    'version': 1,
    'handlers': {
        'custom_handler': {
            'level': 'INFO',
            'class': 'logging_tests.logconfig.MyHandler',
        }
    }
}"""
        self.write_settings('settings.py', sdict={'LOGGING': log_config}) 
Example 18
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def setUpClass(cls):
        super().setUpClass()
        cls._logging = settings.LOGGING
        logging.config.dictConfig(DEFAULT_LOGGING) 
Example 19
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        log_config = """{
    'version': 1,
    'handlers': {
        'custom_handler': {
            'level': 'INFO',
            'class': 'logging_tests.logconfig.MyHandler',
        }
    }
}"""
        self.write_settings('settings.py', sdict={'LOGGING': log_config}) 
Example 20
Project: jbox   Author: jpush   File: django_wsgi.py    License: MIT License 4 votes vote down vote up
def reload_django_settings():
        mod = util.import_module(os.environ['DJANGO_SETTINGS_MODULE'])

        # Reload module.
        reload(mod)

        # Reload settings.
        # Use code from django.settings.Settings module.

        # Settings that should be converted into tuples if they're mistakenly entered
        # as strings.
        tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS")

        for setting in dir(mod):
            if setting == setting.upper():
                setting_value = getattr(mod, setting)
                if setting in tuple_settings and type(setting_value) == str:
                    setting_value = (setting_value,)  # In case the user forgot the comma.
                setattr(settings, setting, setting_value)

        # Expand entries in INSTALLED_APPS like "django.contrib.*" to a list
        # of all those apps.
        new_installed_apps = []
        for app in settings.INSTALLED_APPS:
            if app.endswith('.*'):
                app_mod = util.import_module(app[:-2])
                appdir = os.path.dirname(app_mod.__file__)
                app_subdirs = os.listdir(appdir)
                name_pattern = re.compile(r'[a-zA-Z]\w*')
                for d in sorted(app_subdirs):
                    if (name_pattern.match(d) and
                            os.path.isdir(os.path.join(appdir, d))):
                        new_installed_apps.append('%s.%s' % (app[:-2], d))
            else:
                new_installed_apps.append(app)
        setattr(settings, "INSTALLED_APPS", new_installed_apps)

        if hasattr(time, 'tzset') and settings.TIME_ZONE:
            # When we can, attempt to validate the timezone. If we can't find
            # this file, no check happens and it's harmless.
            zoneinfo_root = '/usr/share/zoneinfo'
            if (os.path.exists(zoneinfo_root) and not
                    os.path.exists(os.path.join(zoneinfo_root,
                        *(settings.TIME_ZONE.split('/'))))):
                raise ValueError("Incorrect timezone setting: %s" %
                        settings.TIME_ZONE)
            # Move the time zone info into os.environ. See ticket #2315 for why
            # we don't do this unconditionally (breaks Windows).
            os.environ['TZ'] = settings.TIME_ZONE
            time.tzset()

        # Settings are configured, so we can set up the logger if required
        if getattr(settings, 'LOGGING_CONFIG', False):
            # First find the logging configuration function ...
            logging_config_path, logging_config_func_name = settings.LOGGING_CONFIG.rsplit('.', 1)
            logging_config_module = util.import_module(logging_config_path)
            logging_config_func = getattr(logging_config_module, logging_config_func_name)

            # ... then invoke it with the logging settings
            logging_config_func(settings.LOGGING) 
Example 21
Project: lexpredict-contraxsuite   Author: LexPredict   File: app_vars.py    License: GNU Affero General Public License v3.0 4 votes vote down vote up
def reset_loggers_level():
    """
    Reset loggers' level from AppVar
    """

    def getEffectiveLevel(self):
        """
        Get the effective level for this logger.

        Loop through this logger and its parents in the logger hierarchy,
        looking for a non-zero logging level. Return the first one found.
        """
        logger = self

        # custom logic
        # cannot use AppVar due to circular import issue
        app_var_level = redis.pop(f'app_var:Logging:logger:{logger.name}:log_level')
        if app_var_level:
            app_var_level = app_var_level.upper()
            if app_var_level in logging._levelToName.values():
                logger.setLevel(app_var_level)

                # log sql to console
                if logger.name == 'django.db.backends':
                    handler = logging.StreamHandler()
                    handler.setLevel(logger.level)
                    logger_handler_classes = [i.__class__ for i in logger.handlers]
                    if redis.pop(f'app_var:Logging:logger:{logger.name}:log_to_console') is True:
                        if handler.__class__ not in logger_handler_classes:
                            logger.addHandler(handler)
                    else:
                        logger.handlers = [i for i in logger.handlers if i.__class__ != handler.__class__]
        # end custom logic

        while logger:
            if logger.level:
                return logger.level
            logger = logger.parent
        return logging.NOTSET

    # reset Project loggers
    for logger_name in settings.LOGGING['loggers']:
        logger = logging.getLogger(logger_name)
        logger.getEffectiveLevel = types.MethodType(getEffectiveLevel, logger)

    # reset celery loggers
    for logger_name in celery_logger_names:
        logger = get_logger(logger_name)
        logger.getEffectiveLevel = types.MethodType(getEffectiveLevel, logger) 
Example 22
Project: Flask-P2P   Author: chalasr   File: django_wsgi.py    License: MIT License 4 votes vote down vote up
def reload_django_settings():
        mod = util.import_module(os.environ['DJANGO_SETTINGS_MODULE'])

        # Reload module.
        reload(mod)

        # Reload settings.
        # Use code from django.settings.Settings module.

        # Settings that should be converted into tuples if they're mistakenly entered
        # as strings.
        tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS")

        for setting in dir(mod):
            if setting == setting.upper():
                setting_value = getattr(mod, setting)
                if setting in tuple_settings and type(setting_value) == str:
                    setting_value = (setting_value,)  # In case the user forgot the comma.
                setattr(settings, setting, setting_value)

        # Expand entries in INSTALLED_APPS like "django.contrib.*" to a list
        # of all those apps.
        new_installed_apps = []
        for app in settings.INSTALLED_APPS:
            if app.endswith('.*'):
                app_mod = util.import_module(app[:-2])
                appdir = os.path.dirname(app_mod.__file__)
                app_subdirs = os.listdir(appdir)
                name_pattern = re.compile(r'[a-zA-Z]\w*')
                for d in sorted(app_subdirs):
                    if (name_pattern.match(d) and
                            os.path.isdir(os.path.join(appdir, d))):
                        new_installed_apps.append('%s.%s' % (app[:-2], d))
            else:
                new_installed_apps.append(app)
        setattr(settings, "INSTALLED_APPS", new_installed_apps)

        if hasattr(time, 'tzset') and settings.TIME_ZONE:
            # When we can, attempt to validate the timezone. If we can't find
            # this file, no check happens and it's harmless.
            zoneinfo_root = '/usr/share/zoneinfo'
            if (os.path.exists(zoneinfo_root) and not
                    os.path.exists(os.path.join(zoneinfo_root,
                        *(settings.TIME_ZONE.split('/'))))):
                raise ValueError("Incorrect timezone setting: %s" %
                        settings.TIME_ZONE)
            # Move the time zone info into os.environ. See ticket #2315 for why
            # we don't do this unconditionally (breaks Windows).
            os.environ['TZ'] = settings.TIME_ZONE
            time.tzset()

        # Settings are configured, so we can set up the logger if required
        if getattr(settings, 'LOGGING_CONFIG', False):
            # First find the logging configuration function ...
            logging_config_path, logging_config_func_name = settings.LOGGING_CONFIG.rsplit('.', 1)
            logging_config_module = util.import_module(logging_config_path)
            logging_config_func = getattr(logging_config_module, logging_config_func_name)

            # ... then invoke it with the logging settings
            logging_config_func(settings.LOGGING)