AlkantarClanX12

Your IP : 18.227.52.248


Current Path : /opt/cloudlinux/venv/lib64/python3.11/site-packages/lvestats/lib/commons/
Upload File :
Current File : //opt/cloudlinux/venv/lib64/python3.11/site-packages/lvestats/lib/commons/logsetup.py

# coding=utf-8
#
# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2019 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT

import logging
import os
from logging.handlers import SysLogHandler

from raven import breadcrumbs
from raven.handlers.logging import SentryHandler

from lvestats.lib.commons.sentry import LveStatsSentryFilter, init_sentry_client

LOGGING_LEVELS = {
    "debug": logging.DEBUG,
    "info": logging.INFO,
    "warning": logging.WARNING,
    "error": logging.ERROR,
    "critical": logging.CRITICAL
}


CONSOLE_LOG = None
SYS_LOG = None
FILE_LOG = None
SENTRY_LOG = None  # type: SentryHandler


def setup_logging(config, caller_name="lvestats",
                  console_level=logging.ERROR,
                  file_level=None):
    """
    Sets up logging
    :param dict|None config: pass None if config wasn't initialized yet, then don't use it.
    :param str caller_name:
    :param console_level:
    :param file_level:
    :return logging.Logger: log, initialized
    """
    logging.root.setLevel(logging.DEBUG)
    init_console_log(console_level)
    init_syslog()
    init_file_log(get_file_logging_level(config, file_level))
    init_sentry_handler(config)
    return logging.getLogger(caller_name)


def init_syslog():
    try:
        global SYS_LOG
        if SYS_LOG is None:
            SYS_LOG = SysLogHandler(address='/dev/log', facility=SysLogHandler.LOG_DAEMON)
            logging.root.addHandler(SYS_LOG)
            formatter_sys = logging.Formatter(fmt='lve-stats: (%(name)s) [%(levelname)s] %(message)s')
            SYS_LOG.setFormatter(formatter_sys)  # write in system log only ERROR-s and FATALLERROR-s
            SYS_LOG.setLevel(logging.ERROR)
    except Exception:
        pass


def init_file_log(file_level):
    log_file_name = '/var/log/lve-stats.log'
    try:
        global FILE_LOG
        if FILE_LOG is None:
            if not os.path.lexists(log_file_name):
                umask_saved = os.umask(0o77)
                with open(log_file_name, 'w', encoding='utf-8'):
                    pass
                os.umask(umask_saved)
            os.chmod(log_file_name, 0o600)
            FILE_LOG = logging.FileHandler(log_file_name)
            logging.root.addHandler(FILE_LOG)
            formatter = logging.Formatter(fmt='%(asctime)s: (%(name)s) [%(levelname)s] %(message)s')
            FILE_LOG.setFormatter(formatter)
        FILE_LOG.setLevel(file_level)
    except Exception:
        pass


def init_sentry_handler(config):
    """
    :param dict config:
    """
    try:
        global SENTRY_LOG
        if SENTRY_LOG is None:
            for logger_name in ["sqlalchemy.pool.NullPool",
                                'main_loop.plugin_executor',
                                'sqlalchemy.orm.mapper.Mapper']:
                breadcrumbs.ignore_logger(logger_name, allow_level=logging.WARNING)
            client = init_sentry_client()
            # client.processors
            SENTRY_LOG = SentryHandler(client)
            sentry_filter = LveStatsSentryFilter()
            SENTRY_LOG.addFilter(sentry_filter)
            client.uncaught_logger.addFilter(sentry_filter)
            logging.root.addHandler(SENTRY_LOG)
            SENTRY_LOG.setLevel(logging.ERROR)
        if SENTRY_LOG and config and "db_type" not in SENTRY_LOG.client.tags:
            SENTRY_LOG.client.tags["db_type"] = config.get("db_type", "None")
            SENTRY_LOG.client.tags["server_id"] = config.get("server_id", "None")
    except Exception:
        pass


def get_file_logging_level(config, file_level):
    if file_level is None:
        if config:
            logging_level = config.get("logging_level", "info").lower()
            if logging_level and logging_level not in LOGGING_LEVELS:
                logging.warning(
                    "Unknown log level: %s. File logging level is set to %s",
                    logging_level,
                    file_level,
                )
                file_level = logging.INFO
            else:
                file_level = LOGGING_LEVELS.get(logging_level, logging.INFO)
        else:
            file_level = logging.CRITICAL
    return file_level


def init_console_log(console_level):
    global CONSOLE_LOG
    if CONSOLE_LOG is None:
        CONSOLE_LOG = logging.StreamHandler()
        logging.root.addHandler(CONSOLE_LOG)
        formatter_console = logging.Formatter(fmt='%(levelname)s : (%(name)s) %(message)s')
        CONSOLE_LOG.setFormatter(formatter_console)
    CONSOLE_LOG.setLevel(console_level)