Ejemplo n.º 1
0
def _setup_logging(level=logging.WARNING):
    """
    Set up logging for the entire module ``privex.rpcemulator`` . Since this is a package, we don't add any
    console or file logging handlers, we purely just set our minimum logging level to WARNING to avoid
    spamming the logs of any application importing it.
    """
    lh = LogHelper(__name__, level=level)
    return lh.get_logger()
Ejemplo n.º 2
0
def set_logging_level(level: int, *loggers: Optional[str], formatter=LOG_FORMATTER):
    lgs = []
    loggers = ['rpcscanner'] if len(loggers) == 0 else loggers
    level = logging.getLevelName(str(level).upper()) if isinstance(level, str) else level
    
    for lg in loggers:
        l_handler = LogHelper(lg, handler_level=level, formatter=formatter)
        l_handler.add_console_handler(level=level, stream=sys.stderr)
        lgs.append(l_handler)
    return lgs
Ejemplo n.º 3
0
def config_logger(*logger_names, log_dir=BASE_LOG_FOLDER):
    """
    Used to allow isolated parts of this project to easily change the log output folder, e.g. allow Django
    management commands to change the logs folder to ``crons/``

    Currently only used by :class:`payments.management.CronLoggerMixin`

    Usage:

    >>> config_logger('someapp', 'otherlogger', 'mylogger', log_dir='/full/path/to/log/folder')

    :param str logger_names: List of logger names to replace logging config for (see LOGGER_NAMES)
    :param str log_dir:      Fully qualified path. Set each logger's timed_file log directory to this
    :return: :class:`logging.Logger` instance of BASE_LOGGER
    """
    _lh = LogHelper(BASE_LOGGER, formatter=LOG_FORMATTER, handler_level=logging.DEBUG)
    _lh.log.handlers.clear()  # Force reset the handlers on the base logger to avoid double/triple logging.
    _lh.add_console_handler(level=CONSOLE_LOG_LEVEL)  # Log to console with CONSOLE_LOG_LEVEL
    
    _dbg_log = os.path.join(log_dir, 'debug.log')
    _err_log = os.path.join(log_dir, 'error.log')
    
    _lh.add_timed_file_handler(_dbg_log, when='D', interval=1, backups=14, level=DBGFILE_LEVEL)
    _lh.add_timed_file_handler(_err_log, when='D', interval=1, backups=14, level=ERRFILE_LEVEL)
    
    l = _lh.get_logger()
    
    # Use the same logging configuration for all privex modules
    _lh.copy_logger(*logger_names)
    
    return l
Ejemplo n.º 4
0
def main():
    global log
    try:
        vargs = parser.parse_args()
    except Exception as e:
        parser.error(f"{type(e)} - {str(e)}")
        return sys.exit(1)
    if vargs.verbose_mode:
        _lh2 = LogHelper('privex.cspgen', handler_level=logging.DEBUG)
        _lh2.add_console_handler(stream=sys.stderr)
        log = _lh2.get_logger()

    log.debug(f"parser args: {vargs!r}")
    if vargs.show_version:
        oprint(COPYRIGHT)
        return COPYRIGHT
    if vargs.show_example:
        exfile, expath = read_example_file()
        exnote = "#####", "#", "# Privex CSPGen example.ini file", f"# Original Location within Python Package: {expath}", "#", "#####\n"
        oprint(*exnote, exfile, *exnote, sep="\n")
        return sys.exit(0)
    filenames = vargs.filenames
    file_sep, sec_sep = literal(vargs.file_sep), literal(vargs.section_sep)
    str_secs = []
    list_secs = []
    if empty(filenames, itr=True):
        if sys.stdin.isatty():
            parser.error("No filenames specified, and no data piped to stdin")
            return sys.exit(1)
        log.debug(
            "Assuming config piped via STDIN. Reading config from stdin.")
        confd = read_stdin()
        builder = get_builder(contents=confd)
        str_secs += [builder.generate('string', sep=sec_sep)]
        list_secs += [builder.generate('list')]
    else:
        for fn in filenames:
            if fn in ['-', '/dev/stdin', 'STDIN']:
                log.debug(
                    "Assuming config piped via STDIN. Reading config from stdin."
                )
                builder = get_builder(contents=read_stdin())
            else:
                builder = get_builder(fn)

            str_secs += [builder.generate('string', sep=sec_sep)]
            list_secs += [builder.generate('list')]

    # oprint('file_sep: ', repr(file_sep))
    # oprint('sec_sep: ', repr(sec_sep))
    oprint(file_sep.join(str_secs))
    return list_secs, str_secs
Ejemplo n.º 5
0
def setup_loggers(*loggers, console=True, file_dbg=True, file_err=True):
    loggers = ['rpcscanner'] if len(loggers) == 0 else loggers
    
    for lg in loggers:
        _lh = LogHelper(lg, formatter=LOG_FORMATTER, handler_level=LOG_LEVEL)
        con, tfh_dbg, tfh_err = None, None, None
        if console: con = _lh.add_console_handler(level=LOG_LEVEL, stream=sys.stderr)
        if file_dbg:
            tfh_dbg = _lh.add_timed_file_handler(
                join(LOG_DIR, 'debug.log'), when='D', interval=1, backups=14, level=LOG_LEVEL
            )
        if file_err:
            tfh_err = _lh.add_timed_file_handler(
                join(LOG_DIR, 'error.log'), when='D', interval=1, backups=14, level=logging.WARNING
            )
        yield con, tfh_dbg, tfh_err, lg
Ejemplo n.º 6
0
def _setup_logging(level=logging.WARNING):
    """
    Set up logging for the entire module ``privex.eos`` . Since this is a package, we don't add any
    console or file logging handlers, we purely just set our minimum logging level to WARNING to avoid
    spamming the logs of any application importing it.
    """
    try:
        from privex.loghelper import LogHelper
        lh = LogHelper(__name__, level=level)
        return lh.get_logger()
    except ImportError:
        warnings.warn(
            f'{__name__} failed to import privex.loghelper. Logging may not work as expected.'
        )
        lh = logging.getLogger(__name__)
        lh.setLevel(logging.WARNING)
        return log
Ejemplo n.º 7
0
 def __init__(self):
     LogHelper('historyapp.tasks').copy_logger('historyapp.lib.loader')
     global log
     _l = logging.getLogger('historyapp.lib.loader')
     _l.propagate = False
     _l.handlers.clear()
     log = logging.getLogger(__name__)
     log.propagate = False
     log.handlers.clear()
Ejemplo n.º 8
0
def set_logging_level(level: Union[str, int] = None, logger='colfixer'):
    global log
    if empty(level):
        level = 'ERROR' if settings.QUIET else env(
            'LOG_LEVEL', ('DEBUG' if settings.DEBUG else 'WARNING'))
    if isinstance(level, str):
        level = logging.getLevelName(level)
    _lh = LogHelper(logger, handler_level=level)
    _lh.add_console_handler()
    if logger == 'colfixer':
        log = _lh.get_logger()
    return _lh.get_logger()
Ejemplo n.º 9
0
            }
        ]],
        extensions=[],
        signatures=[
            '1f1a0212f7b9fe263acaeadf1ec127000dc234c413b543e3c268d251e8d8205b95746f3aa102805eb85d5ee72bf1c80b7'
            + '14fadf081d29138a6ddab085dafa28604'
        ]),
    'txid':
    'c901c52daf57b60242d9d7be67f790e023cf2780',
}]

IGNORE_KEYS_FIND = ['transaction_id', 'block_num', 'transaction_num']

DEBUG = env_bool('DEBUG', False)

lh = LogHelper('golos',
               handler_level=logging.DEBUG if DEBUG else logging.CRITICAL)
lh.add_console_handler()
log = lh.get_logger()


class GolosTestCase(unittest.TestCase):
    def setUp(self):
        self.golos = Api(nodes=NODES, report=DEBUG)

    def test_get_account(self):
        """Testing Api.get_accounts returns valid account dictionaries"""
        a = self.golos.get_accounts(TEST_ACCOUNTS)
        self.assertIs(type(a), list)
        self.assertEqual(len(a), len(TEST_ACCOUNTS))
        for i, acc in enumerate(a):
            # log.info('get_accounts %s = %s', acc, a)
Ejemplo n.º 10
0
#######################################
#
# Logging Configuration
#
#######################################

# Log to console with CONSOLE_LOG_LEVEL, as well as output logs >=info / >=warning to respective files
# with automatic daily log rotation (up to 14 days of logs)
# Due to the amount of output from logging.DEBUG, we only log INFO and higher to a file.
# Valid environment log levels (from least to most severe) are:
# DEBUG, INFO, WARNING, ERROR, FATAL, CRITICAL

LOG_FORMATTER = logging.Formatter('[%(asctime)s]: %(name)-25s -> %(funcName)-20s : %(levelname)-8s:: %(message)s')

lh = LogHelper('lg', formatter=LOG_FORMATTER)

CONSOLE_LOG_LEVEL = env('LOG_LEVEL', None)
CONSOLE_LOG_LEVEL = logging.getLevelName(str(CONSOLE_LOG_LEVEL).upper()) if CONSOLE_LOG_LEVEL is not None else None

if CONSOLE_LOG_LEVEL is None:
    CONSOLE_LOG_LEVEL = logging.DEBUG if cf['DEBUG'] else logging.INFO

lh.add_console_handler(level=CONSOLE_LOG_LEVEL)

DBG_LOG, ERR_LOG = os.path.join(BASE_DIR, 'logs', 'debug.log'), os.path.join(BASE_DIR, 'logs', 'error.log')
lh.add_timed_file_handler(DBG_LOG, when='D', interval=1, backups=14, level=CONSOLE_LOG_LEVEL)
lh.add_timed_file_handler(ERR_LOG, when='D', interval=1, backups=14, level=logging.WARNING)

log = lh.get_logger()
lh.copy_logger('privex')
Ejemplo n.º 11
0
def _setup_logging(level=logging.WARNING):
    lh = LogHelper(__name__, level=level)
    return lh.get_logger()
Ejemplo n.º 12
0
import shlex
import operator
import time
import logging
from dotenv import load_dotenv
from socket import gethostbyaddr, herror
from privex.helpers import env_bool
from privex.loghelper import LogHelper
from os import getenv as env

load_dotenv()

use_docker = env_bool('USE_DOCKER', True)
docker_name = env('DOCKER_NAME', 'seed')

_lh = LogHelper('privex.steempeers', handler_level=logging.DEBUG)
_lh.add_console_handler()

log = _lh.get_logger()

# If USE_DOCKER is True, obtain the PID of the docker container, then use nsenter
# to run netstat inside of the containers network stack
if use_docker:
    cmd = shlex.split("docker inspect -f '{{.State.Pid}}' " + docker_name)

    pid = ""
    # print(cmd)
    with subprocess.Popen(cmd, stdout=subprocess.PIPE) as proc:
        pid = proc.stdout.read().decode('utf-8')
    log.debug('steemd docker pid is: %s', pid)
    cmd = shlex.split("nsenter -t " + pid + " -n netstat -avWetn")
Ejemplo n.º 13
0
    +===================================================+
    |                                                   |
    |        Steem RPC Load Balancer                    |
    |                                                   |
    |        Core Developer(s):                         |
    |                                                   |
    |          (+)  Chris (@someguy123) [Privex]        |
    |                                                   |
    +===================================================+

"""
import logging
from privex.loghelper import LogHelper
from balancer.core import cf, CONSOLE_LOG_LEVEL, DBG_LOG, ERR_LOG
from balancer.app import flask

lh = LogHelper(__name__)

lh.add_console_handler(level=CONSOLE_LOG_LEVEL)

lh.add_timed_file_handler(DBG_LOG,
                          when='D',
                          interval=1,
                          backups=14,
                          level=logging.INFO)
lh.add_timed_file_handler(ERR_LOG,
                          when='D',
                          interval=1,
                          backups=14,
                          level=logging.WARNING)
Ejemplo n.º 14
0
def setup_logging(log_level=logging.INFO):
    from privex.loghelper import LogHelper
    lh = LogHelper(__name__, handler_level=log_level)
    lh.add_console_handler()
Ejemplo n.º 15
0
from privex.loghelper import LogHelper
from privex.helpers.cache import AsyncMemoryCache, adapter_set
from dotenv import load_dotenv
from os import getenv as env

load_dotenv()
nest_asyncio.apply()

CACHE_TIMEOUT = env_int('CACHE_TIMEOUT', 300)
LOOP_SLEEP = env_cast('LOOP_SLEEP', float, 60.0)

DEFAULT_FROM = env('DEFAULT_FROM', 'hive')
DEFAULT_TO = env('DEFAULT_TO', 'usd')
DEFAULT_AMOUNT = env_cast('DEFAULT_AMOUNT', float, 1)

LogHelper(level=logging.ERROR, handler_level=logging.ERROR)
_lh = LogHelper('steemvalue')
h = _lh.add_console_handler()

# LogHelper('privex.exchange', handler_level=logging.DEBUG, clear_handlers=False)

logging.basicConfig()

log = _lh.get_logger()
log.propagate = False
# log = logging.getLogger()

adapter_set(AsyncMemoryCache())

app = Flask(__name__)
Ejemplo n.º 16
0
import logging

# BASE_DIR = dirname(abspath(__file__))
app = Flask(__name__)
CORS(app)
cf = app.config

app.url_map.strict_slashes = False

for k, v in settings.cf.items():
    cf[k] = v

# if empty(LOG_LEVEL):
#     LOG_LEVEL = logging.DEBUG if DEBUG else logging.INFO

lh = LogHelper('myip')
if settings.USE_RICH_LOGGING:
    lh.get_logger().addHandler(
        RichHandler(level=settings.LOG_LEVEL,
                    console=console_err,
                    rich_tracebacks=settings.RICH_TRACEBACKS))
else:
    lh.add_console_handler(level=settings.LOG_LEVEL, stream=sys.stderr)

lh.add_timed_file_handler(settings.DBG_LOG,
                          when='D',
                          interval=1,
                          backups=14,
                          level=settings.LOG_LEVEL)
lh.add_timed_file_handler(settings.ERR_LOG,
                          when='D',
Ejemplo n.º 17
0
from typing import Tuple, List, Union

from privex.helpers import empty
from quart import request
from quart.exceptions import BadRequest
from rethinkdb import RethinkDB
from rethinkdb.ast import DB
from rethinkdb.net import DefaultConnection

from postfixparser import settings
from privex.loghelper import LogHelper

from postfixparser.settings import AppError, DEFAULT_ERR, ERRORS

_lh = LogHelper('postfixparser')
_lh.add_console_handler(level=logging.INFO)

log = logging.getLogger(__name__)

__STORE = {}


async def get_rethink() -> Tuple[DB, DefaultConnection, RethinkDB]:
    """

    Usage:

        >>> from postfixparser.core import get_rethink
        >>>
        >>> r, conn, rDB = await get_rethink()
Ejemplo n.º 18
0
"""
import logging
import os
from django.test import TestCase

from privex.loghelper import LogHelper
from os import getenv as env

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "lockmgr.settings")
from lockmgr.lockmgr import LockMgr, Locked, Lock, get_lock, unlock, is_locked, renew_lock, LockNotFound

LOG_LEVEL = env('LOG_LEVEL')
LOG_LEVEL = logging.getLevelName(str(LOG_LEVEL).upper()) if LOG_LEVEL is not None else logging.WARNING
LOG_FORMATTER = logging.Formatter('[%(asctime)s]: %(name)-55s -> %(funcName)-20s : %(levelname)-8s:: %(message)s')
_lh = LogHelper('lockmgr.tests', handler_level=LOG_LEVEL, formatter=LOG_FORMATTER)
_lh.add_console_handler()
log = _lh.get_logger()


class LockMgrTestBase(TestCase):
    """
    Base class for all django-lockmgr test classes. Includes :meth:`.tearDown` to delete all locks after each test.
    """
    def tearDown(self) -> None:
        """Ensure all locks are deleted after each test"""
        locks_removed = Lock.objects.all().delete()
        log.debug('tearDown -> Removed %d locks', locks_removed[0])


__all__ = [
Ejemplo n.º 19
0
    modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:
    
    The above copyright notice and this permission notice shall be included in all copies or substantial portions of
    the Software.
    
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
    WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
    OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
    OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    
    Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or
    otherwise to promote the sale, use or other dealings in this Software without prior written authorization.


"""

import logging
import sys

from privex.loghelper import LogHelper
from privex.iota.client import PrivexIota
from privex.iota.objects import Neighbor, NodeInfo, NeighborRes
from privex.iota.status import print_intro, gen_cols, iter_cols, main as iota_status_app, load_node_info

name = 'iota'
VERSION = '0.8.0'

_lh = LogHelper(__name__, handler_level=logging.INFO)
_lh.add_console_handler(stream=sys.stderr)
Ejemplo n.º 20
0
    |                                                   |
    |        Core Developer(s):                         |
    |                                                   |
    |          (+)  Chris (@someguy123) [Privex]        |
    |                                                   |
    +===================================================+

    CDN Builder - A tool written in Python for building and version organising compiled JS/CSS assets
    Copyright (c) 2019    Privex Inc. ( https://www.privex.io )

    This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General
    Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option)
    any later version.

    This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
    warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
    details.

    You should have received a copy of the GNU Affero General Public License along with this program.
    If not, see <https://www.gnu.org/licenses/>.


"""
from privex.loghelper import LogHelper
from cdnbuilder.settings import LOG_LEVEL

lh = LogHelper('cdnbuilder', handler_level=LOG_LEVEL)
lh.add_console_handler()

VERSION = '0.9.0'
Ejemplo n.º 21
0
    def handle(self, *args, **options):

        _lh = LogHelper(__name__,
                        formatter=LOG_FORMATTER,
                        handler_level=logging.INFO)
        _lh.add_console_handler()
        _lh.get_logger().propagate = False
        lockmgr.clean_locks()  # Clean up any locks due for expiration.

        fail = is_true(options['fail'])
        no_renew = is_true(options['no_renew'])
        only_renew = is_true(options['only_renew'])
        no_timeout = is_true(options['no_timeout'])

        locks: list = options['locks']
        process_id: int = int(options['process_id']
                              ) if options['process_id'] is not None else None
        locked_by: str = options['locked_by']
        timeout = None if no_timeout else int(options['timeout'])
        lock_args = dict(expires=timeout,
                         locked_by=locked_by,
                         lock_process=process_id)
        if len(locks) == 0:
            print('No lock names specified.')
            return

        _create = False if only_renew else True
        _renew = False if no_renew else True

        try:
            res = set_lock(*locks,
                           timeout=timeout,
                           locked_by=locked_by,
                           process_id=process_id,
                           fail=fail,
                           create=_create,
                           renew=_renew)
            print(f"Finished creating / renewing {len(locks)} locks.\n")

            print("\n====================Status Report=====================\n")
            print(f"  Per-lock:\n")
            print("\t\t{:<20}{:<20}{:<20}{:<20}\n".format(
                "Name", "Was Locked?", "Now Locked?", "Status"))
            for lck_name, lres in res.statuses:
                print("\t\t{:<20}{:<20}{:<20}{:<20}".format(
                    lck_name, 'YES' if lres.was_locked else 'NO',
                    'YES' if lres.locked else 'NO', lres.status))
            print(
                "\n========================================================\n")
            print("  Summary:\n")
            print(f"    Locks Created:      {res.counts['created']}")
            print(f"    Locks Renewed:      {res.counts['renewed']}")
            print(f"    Renewals Skipped:   {res.counts['skip_renew']}")
            print(f"    Creations Skipped:  {res.counts['skip_create']}")

        except LockFail as e:
            print(
                "\n---------------------------------------------------------------------------\n"
            )
            print(
                " [lockmgr.management.commands.set_lock] Caught exception LockFail while creating/setting locks..."
            )
            print(
                " [lockmgr.management.commands.set_lock] The following existing lock was encountered:\n"
            )
            print(f"\t{e.lock}\n")
            print(
                " >>> As you have set -e / --fail, this means that any lock creations or updates triggered during "
                "this run of set_lock should have been rolled back.")
            print(
                " >>> If in doubt, run './manage.py list_locks' to view all current locks.\n"
            )
            print(" !!! Now exiting with return code 2...\n")
            return sys.exit(2)

        print("")
        print("\n=========================================================\n")
        print("Finished creating / renewing locks.")
        print("\n=========================================================\n")
Ejemplo n.º 22
0
    str(LOG_LEVEL).upper()) if LOG_LEVEL is not None else None

if LOG_LEVEL is None:
    LOG_LEVEL = logging.DEBUG if DEBUG else logging.INFO

LOG_FORMATTER = logging.Formatter(
    '[%(asctime)s]: %(name)-55s -> %(funcName)-20s : %(levelname)-8s:: %(message)s'
)
# LOG_FORMATTER = logging.Formatter('[%(asctime)s]: %(funcName)-14s : %(levelname)-8s:: %(message)s')

LOG_DIR = env('LOG_DIR', BASE_DIR / 'logs')

if not LOG_DIR.exists():
    os.makedirs(str(LOG_DIR))

_lh = LogHelper('pinapp', formatter=LOG_FORMATTER, handler_level=logging.DEBUG)

# Log to console with LOG_LEVEL, as well as output logs >=debug / >=warning to respective files
# with automatic daily log rotation (up to 14 days of logs)
_lh.add_console_handler(level=LOG_LEVEL)
_lh.add_timed_file_handler(str(BASE_DIR / 'logs' / 'debug.log'),
                           when='D',
                           interval=1,
                           backups=14,
                           level=LOG_LEVEL)
_lh.add_timed_file_handler(str(BASE_DIR / 'logs' / 'error.log'),
                           when='D',
                           interval=1,
                           backups=14,
                           level=logging.WARNING)
Ejemplo n.º 23
0
import logging
import argparse
from privex.loghelper import LogHelper
from typing import Union, Optional, List, Tuple, Dict, Set

__all__ = [
    'CSPBuilder', 'get_builder', 'main', 'parser', 'log_level', 'PKG_DIR',
    'EXAMPLE_DIR', 'EXAMPLE_INI'
]

PKG_DIR = Path(__file__).parent.resolve()
EXAMPLE_DIR = PKG_DIR / 'examples'
EXAMPLE_INI = EXAMPLE_DIR / 'example.ini'

log_level = env('LOG_LEVEL', 'WARNING')
_lh = LogHelper('privex.cspgen', handler_level=logging.getLevelName(log_level))
_lh.add_console_handler(stream=sys.stderr)

log = _lh.get_logger()

argc, argv = len(sys.argv), sys.argv


class CSPBuilder:
    def __init__(self,
                 filename: str = None,
                 file_handle=None,
                 contents: Union[str, list, tuple] = None,
                 **kwargs):
        self.config = configparser.ConfigParser()
        self.conf_file = None
Ejemplo n.º 24
0
from typing import List, Union, Dict

from privex.loghelper import LogHelper

from tests.base import PrivexBaseCase
from privex.helpers import thread as modthread, LockConflict, random_str, OrderedDictObject
from privex.helpers.thread import BetterEvent, event_multi_wait_all, event_multi_wait_any, lock_acquire_timeout, SafeLoopThread
from collections import namedtuple
from threading import Event, Lock
import threading
import queue

import logging

LOG_FORMATTER = logging.Formatter('[%(asctime)s]: %(name)-25s -> %(funcName)-35s : %(levelname)-8s:: %(message)s')
_lh = LogHelper(__name__, handler_level=logging.DEBUG, formatter=LOG_FORMATTER)
_lh.add_console_handler()
_lh.copy_logger('privex.helpers.thread')

log = logging.getLogger(__name__)

# release_lock = BetterEvent(name='Global Release Lock event')
shared_lock = threading.Lock()
shared_queue = queue.Queue()

stop_threads = BetterEvent(name='Global stop_threads')
            
LockCheck = namedtuple('LockCheck', 'thread_id was_locked lock_exception thread_name')
UnlockEvent = namedtuple('UnlockEvent', 'thread_id thread_name')

Ejemplo n.º 25
0
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
    INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
    PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
    OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


"""

import logging
import unittest
from privex.loghelper import LogHelper
from privex.helpers import env_bool
from privex.rpcemulator.base import Emulator
from tests.test_bitcoin import TestBitcoinEmulator

Emulator.use_coverage = True

if env_bool('DEBUG', False) is True:
    LogHelper('privex.rpcemulator',
              level=logging.DEBUG).add_console_handler(logging.DEBUG)
else:
    LogHelper('privex.rpcemulator',
              level=logging.CRITICAL)  # Silence non-critical log messages
    Emulator.quiet = True  # Disable HTTP logging

if __name__ == '__main__':
    unittest.main()
Ejemplo n.º 26
0
from privex.loghelper import LogHelper
import os
from os import getenv as env
import logging

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = False
SECRET_KEY = 'NotApplicable'

LOG_FORMATTER = logging.Formatter(
    '[%(asctime)s]: %(name)-55s -> %(funcName)-20s : %(levelname)-8s:: %(message)s'
)

LOG_LEVEL = logging.WARNING

_lh = LogHelper('adminplus', formatter=LOG_FORMATTER, handler_level=LOG_LEVEL)

_lh.add_console_handler()

INSTALLED_APPS = ['django_nose', 'adminplus']

DATABASES = {}

TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'

if env('DB_BACKEND', 'sqlite') in ['sqlite', 'sqlite3']:
    DATABASES = dict(default=dict(ENGINE='django.db.backends.sqlite3',
                                  NAME=os.path.join(
                                      BASE_DIR, env('DB_PATH', 'db.sqlite3'))))
else:
    DATABASES = {
Ejemplo n.º 27
0
from privex.loghelper import LogHelper
import os
from os import getenv as env
import logging

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = False
SECRET_KEY = 'NotApplicable'

LOG_FORMATTER = logging.Formatter('[%(asctime)s]: %(name)-55s -> %(funcName)-20s : %(levelname)-8s:: %(message)s')

LOG_LEVEL = logging.WARNING

_lh = LogHelper('lockmgr', formatter=LOG_FORMATTER, handler_level=LOG_LEVEL)

_lh.add_console_handler()

INSTALLED_APPS = ['django_nose', 'lockmgr']

DATABASES = {}

TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'

USE_I18N = True
USE_L10N = True
USE_TZ = True

if env('DB_BACKEND', 'sqlite') in ['sqlite', 'sqlite3']:
Ejemplo n.º 28
0
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of 
the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or 
otherwise to promote the sale, use or other dealings in this Software without prior written authorization.
"""
import sys

from privex.pyrewall.conf import LOG_LEVEL
from privex.pyrewall.core import find_file, valid_port
from privex.pyrewall.RuleParser import RuleParser
from privex.pyrewall.RuleBuilder import RuleBuilder
from privex.pyrewall.PyreParser import PyreParser
from privex.pyrewall.types import IPT_ACTION, IPT_TYPE
from privex.pyrewall.exceptions import RuleSyntaxError, InvalidPort
from privex.loghelper import LogHelper

name = 'pyrewall'
VERSION = '0.12.0'

_lh = LogHelper(__name__, handler_level=LOG_LEVEL)

_lh.add_console_handler(stream=sys.stderr)
Ejemplo n.º 29
0
from privex.helpers import dictable_namedtuple, Mocker
from privex.db import SqliteWrapper, BaseQueryBuilder, SqliteQueryBuilder, QueryMode
from privex.db import _setup_logging
from privex.db.sqlite import SqliteAsyncWrapper

try:
    dotenv.read_dotenv()
except AttributeError:
    dotenv.load_dotenv()


LOG_LEVEL = env('LOG_LEVEL')
LOG_LEVEL = logging.getLevelName(str(LOG_LEVEL).upper()) if LOG_LEVEL is not None else logging.WARNING
_setup_logging(LOG_LEVEL)
LOG_FORMATTER = logging.Formatter('[%(asctime)s]: %(name)-55s -> %(funcName)-20s : %(levelname)-8s:: %(message)s')
_lh = LogHelper('privex.db.tests', handler_level=LOG_LEVEL, formatter=LOG_FORMATTER)
_lh.copy_logger('privex.db')
_lh.add_console_handler()
log = _lh.get_logger()


class PrivexTestBase(TestCase):
    pass


class PrivexDBTestBase(PrivexTestBase):
    """
    Base class for all privex-db test classes. Includes :meth:`.tearDown` to reset database after each test.
    """

    def setUp(self) -> None:
Ejemplo n.º 30
0
from ZCoinAdapter import ZCoinAdapter
from adapters.BittrexAdapter import BittrexAdapter
from models import db

app = Flask(__name__)

BASE_DIR = abspath(dirname(abspath(__file__)))
LOG_DIR = join(BASE_DIR, 'logs')

# Load settings from the config file
app.config.from_pyfile('znode.cfg')

if app.config['DEBUG']:
    app.config['TEMPLATES_AUTO_RELOAD'] = True

_lh = LogHelper(handler_level=logging.DEBUG)

_lh.add_console_handler()
_lh.add_timed_file_handler(join(LOG_DIR, 'debug.log'),
                           level=logging.DEBUG,
                           when='D',
                           interval=7,
                           backups=4)
_lh.add_timed_file_handler(join(LOG_DIR, 'error.log'),
                           level=logging.WARNING,
                           when='D',
                           interval=7,
                           backups=4)

log = logging.getLogger(__name__)