예제 #1
0
파일: logger.py 프로젝트: matham/moa
def logger_config_update(section, key, value):
    '''Callback called when the :attr:`~moa.config.Config` object changes the
    `log_level` key value.
    '''
    if LOG_LEVELS.get(value) is None:
        raise AttributeError('Loglevel {0!r} doesn\'t exists'.format(value))
    Logger.setLevel(level=LOG_LEVELS.get(value))
예제 #2
0
        def build(self):
            Window.size = (1024, 768)
            self.sm = ScreenManager()
            self.sm.add_widget(StartScreen(name='start'))
            self.sm.add_widget(GcodeViewerScreen(name='gcode'))
            self.sm.add_widget(ExitScreen(name='main'))
            self.sm.current = 'gcode'

            level = LOG_LEVELS.get('debug') if len(
                sys.argv) > 2 else LOG_LEVELS.get('info')
            Logger.setLevel(level=level)
            # logging.getLogger().setLevel(logging.DEBUG)
            return self.sm
예제 #3
0
def configure_sentry(in_debug=False):
    """
    Configure the Raven client, or create a dummy one if `in_debug` is `True`.
    """
    key = 'b290ecc8934f4cb599e6fa6af6cc5cc2'
    # the public DSN URL is not available on the Python client
    # so we're exposing the secret and will be revoking it on abuse
    # https://github.com/getsentry/raven-python/issues/569
    secret = '0ae02bcb5a75467d9b4431042bb98cb9'
    project_id = '1111738'
    dsn = 'https://{key}:{secret}@sentry.io/{project_id}'.format(
        key=key, secret=secret, project_id=project_id)
    if in_debug:
        client = DebugRavenClient()
    else:
        client = Client(dsn=dsn, release=__version__)
        # adds context for Android devices
        if platform == 'android':
            from jnius import autoclass
            Build = autoclass("android.os.Build")
            VERSION = autoclass('android.os.Build$VERSION')
            android_os_build = {
                'model': Build.MODEL,
                'brand': Build.BRAND,
                'device': Build.DEVICE,
                'manufacturer': Build.MANUFACTURER,
                'version_release': VERSION.RELEASE,
            }
            client.user_context({'android_os_build': android_os_build})
        # Logger.error() to Sentry
        # https://docs.sentry.io/clients/python/integrations/logging/
        handler = SentryHandler(client)
        handler.setLevel(LOG_LEVELS.get('error'))
        setup_logging(handler)
    return client
예제 #4
0
    def main():
        # when the -d/--debug flag is set, Kivy sets log level to debug
        level = Logger.getEffectiveLevel()
        in_debug = level == LOG_LEVELS.get('debug')

        reset()
        MainApp().run()
        print("Returned from run")
예제 #5
0
파일: main.py 프로젝트: vesellov/recotra
 def build(self):
     level = LOG_LEVELS.get('debug')
     Logger.setLevel(level=level)
     logging.getLogger().setLevel(logging.DEBUG)
     local_storage.init()
     self.title = 'RECOTRA'
     self.icon = './icons/btcusd.ico'
     self.main_window = main_window.MainWindow()
     return self.main_window
def init_logger(logger):
    """Setting up the Kivy logger.
    """

    # Set log level
    log_level = 'debug'
    log_level_code = LOG_LEVELS.get(log_level.lower())
    logger.setLevel(log_level_code)

    # DEBUG
    logger.info('Setting up Scissors Logger: Hello Logger :)')
예제 #7
0
파일: main.py 프로젝트: onuratakan/QrScan
def main():
    # when the -d/--debug flag is set, Kivy sets log level to debug
    level = Logger.getEffectiveLevel()
    in_debug = level == LOG_LEVELS.get('debug')
    client = configure_sentry(in_debug)
    try:
        MainApp().run()
    except Exception:
        if type(client) == Client:
            Logger.info(
                'Errors will be sent to Sentry, run with "--debug" if you '
                'are a developper and want to the error in the shell.')
        client.captureException()
예제 #8
0
def require(version):
    '''Require can be used to check the minimum version required to run a Kivy
    application. For example, you can start your application code like this::

        import kivy
        kivy.require('1.0.1')

    If a user attempts to run your application with a version of Kivy that is
    older than the specified version, an Exception is raised.

    The Kivy version string is built like this::

        X.Y.Z[tag[tagrevision]]

        X is the major version
        Y is the minor version
        Z is the bugfixes revision

    The tag is optional, but may be one of '.dev', '.post', 'a', 'b', or 'rc'.
    The tagrevision is the revision number of the tag.

    .. warning::

        You must not ask for a version with a tag, except -dev. Asking for a
        'dev' version will just warn the user if the current Kivy
        version is not a -dev, but it will never raise an exception.
        You must not ask for a version with a tagrevision.

    '''

    # user version
    revision, tag, tagrev = parse_kivy_version(version)
    # current version
    sysrevision, systag, systagrev = parse_kivy_version(__version__)

    Logger.log(LOG_LEVELS.get('info'), f"Kivy: Using Kivy version {int(sysrevision[0])}.{int(sysrevision[1])}.{int(sysrevision[2])}.{systag}{systagrev}")

    if tag and not systag:
        Logger.warning('Application requested a dev version of Kivy. '
                       '(You have %s, but the application requires %s)' % (
                           __version__, version))
    # not tag rev (-alpha-1, -beta-x) allowed.
    if tagrev is not None:
        raise Exception('Revision format must not contain any tagrevision')

    # finally, checking revision
    if sysrevision < revision:
        raise Exception('The version of Kivy installed on this system '
                        'is too old. '
                        '(You have %s, but the application requires %s)' % (
                            __version__, version))
예제 #9
0
파일: __init__.py 프로젝트: kod3r/kivy
            Add an input provider (eg: ccvtable1:tuio,192.168.0.1:3333).
        -m mod, --module=mod
            Activate a module (use "list" to get a list of available modules).
        -r, --rotation
            Rotate the window's contents (0, 90, 180, 270).
        -s, --save
            Save current Kivy configuration.
        --size=640x480
            Size of window geometry.
    '''
    print kivy_usage.__doc__ % (basename(sys.argv[0]))


# Start !
if 'vim' in globals():
    Logger.setLevel(level=LOG_LEVELS.get('critical'))
else:
    Logger.setLevel(level=LOG_LEVELS.get('info'))
    Logger.info('Kivy v%s' % (__version__))

#: Global settings options for kivy
kivy_options = {
    'window': ('pygame', ),
    'text': ('pil', 'pygame'),
    'video': ('ffmpeg', 'gstreamer', 'pyglet'),
    'audio': (
        'pygame',
        'gstreamer',
    ),
    'image': ('dds', 'gif', 'pil', 'pygame'),
    'camera': ('opencv', 'gstreamer', 'videocapture'),
예제 #10
0
            Activate a module (use "list" to get a list of available modules).
        -r, --rotation
            Rotate the window's contents (0, 90, 180, 270).
        -s, --save
            Save current Kivy configuration.
        --size=640x480
            Size of window geometry.
        --dpi=96
            Manually overload the Window DPI (for testing only.)
    '''
    print(kivy_usage.__doc__ % (basename(sys.argv[0])))


# Start !
if 'vim' in globals():
    Logger.setLevel(level=LOG_LEVELS.get('critical'))
else:
    Logger.setLevel(level=LOG_LEVELS.get('info'))
    Logger.info('Kivy v%s' % (__version__))

#: Global settings options for kivy
kivy_options = {
    'window': ('egl_rpi', 'pygame', 'sdl', 'x11'),
    'text': ('pil', 'pygame', 'sdlttf'),
    'video': ('gstplayer', 'ffmpeg', 'gi', 'pygst', 'pyglet', 'null'),
    'audio': ('gstplayer', 'pygame', 'gi', 'pygst', 'sdl'),
    'image': ('tex', 'imageio', 'dds', 'gif', 'pil', 'pygame'),
    'camera': ('opencv', 'gi', 'pygst', 'videocapture', 'avfoundation'),
    'spelling': ('enchant', 'osxappkit', ),
    'clipboard': ('android', 'pygame', 'dummy'), }
예제 #11
0
파일: __init__.py 프로젝트: krishardy/kivy
            mkdir(kivy_home_dir)
        if not exists(kivy_usermodules_dir):
            mkdir(kivy_usermodules_dir)
        if not exists(kivy_userexts_dir):
            mkdir(kivy_userexts_dir)
        if not exists(icon_dir):
            try:
                shutil.copytree(join(kivy_data_dir, 'logo'), icon_dir)
            except:
                Logger.exception('Error when copying logo directory')

    # configuration
    from kivy.config import Config

    # Set level of logger
    level = LOG_LEVELS.get(Config.get('kivy', 'log_level'))
    Logger.setLevel(level=level)

    # Can be overrided in command line
    if 'KIVY_UNITTEST' not in environ and 'KIVY_PACKAGING' not in environ:
        # save sys argv, otherwize, gstreamer use it and display help..
        sys_argv = sys.argv
        sys.argv = sys.argv[:1]

        try:
            opts, args = getopt(sys_argv[1:], 'hp:fkawFem:sr:dc:', [
                'help', 'fullscreen', 'windowed', 'fps', 'event',
                'module=', 'save', 'fake-fullscreen', 'auto-fullscreen',
                'display=', 'size=', 'rotate=', 'config=', 'debug',
                'dpi='])
예제 #12
0
파일: __init__.py 프로젝트: dhootha/kivy
            mkdir(kivy_home_dir)
        if not exists(kivy_usermodules_dir):
            mkdir(kivy_usermodules_dir)
        if not exists(kivy_userexts_dir):
            mkdir(kivy_userexts_dir)
        if not exists(icon_dir):
            try:
                shutil.copytree(join(kivy_data_dir, 'logo'), icon_dir)
            except:
                Logger.exception('Error when copying logo directory')

    # configuration
    from kivy.config import Config

    # Set level of logger
    level = LOG_LEVELS.get(Config.get('kivy', 'log_level'))
    Logger.setLevel(level=level)

    # Can be overrided in command line
    if ('KIVY_UNITTEST' not in environ and 'KIVY_PACKAGING' not in environ
            and 'KIVY_NO_ARGS' not in environ):
        # save sys argv, otherwize, gstreamer use it and display help..
        sys_argv = sys.argv
        sys.argv = sys.argv[:1]

        try:
            opts, args = getopt(sys_argv[1:], 'hp:fkawFem:sr:dc:', [
                'help', 'fullscreen', 'windowed', 'fps', 'event', 'module=',
                'save', 'fake-fullscreen', 'auto-fullscreen', 'display=',
                'size=', 'rotate=', 'config=', 'debug', 'dpi='
            ])
예제 #13
0
파일: main.py 프로젝트: cryptobuks/QrScan
            client.user_context({'android_os_build': android_os_build})
        # Logger.error() to Sentry
        # https://docs.sentry.io/clients/python/integrations/logging/
        handler = SentryHandler(client)
        handler.setLevel(LOG_LEVELS.get('error'))
        setup_logging(handler)
    return client


class MainApp(App):

    theme_cls = ThemeManager()

    def build(self):
        self.icon = "docs/images/icon.png"


if __name__ == '__main__':
    # when the -d/--debug flag is set, Kivy sets log level to debug
    level = Logger.getEffectiveLevel()
    in_debug = level == LOG_LEVELS.get('debug')
    client = configure_sentry(in_debug)
    try:
        MainApp().run()
    except Exception:
        if type(client) == Client:
            Logger.info(
                'Errors will be sent to Sentry, run with "--debug" if you '
                'are a developper and want to the error in the shell.')
        client.captureException()
예제 #14
0
def bookblock(source_dir, target_dir, source_file_format, target_file_format,
              pages, geometry, image_mode, view_mode, examples, debug):
    """Cut out pages from book scans.
    """

    # Resetting `sys.argv':
    #
    # The bookblock command line options disturb Kivy:
    # See file site-packages/kivy/__init__.py :
    #
    #     try:
    #         opts, args = getopt(sys_argv[1:], 'hp:fkawFem:sr:dc:', [
    #             'help', 'fullscreen', 'windowed', 'fps', 'event',
    #             'module=', 'save', 'fake-fullscreen', 'auto-fullscreen',
    #             'multiprocessing-fork', 'display=', 'size=', 'rotate=',
    #             'config=', 'debug', 'dpi='])
    #
    #     except GetoptError as err:
    #         Logger.error('Core: %s' % str(err))
    #         kivy_usage()
    #
    # Example: the option `--source-dir <dir>' causes the following error:
    #
    #   Core: option --source-dir not recognized
    #
    # Therefore only options relevant for Kivy should be
    # contained in sys.argv when starting to deal with Kivy code:
    sys.argv = [sys.argv[1]]

    if debug in ['trace', 'debug', 'info']:
        print("DEBUG bookblock:")
        print("")
        print("  - source_dir:         {}".format(source_dir))
        print("  - target_dir:         {}".format(target_dir))
        print("  - source_file_format: {}".format(source_file_format))
        print("  - target_file_format: {}".format(target_file_format))
        print("  - pages:              {}".format(pages))
        print("  - geometry:           {}".format(geometry))
        print("  - image_mode:         {}".format(image_mode))
        print("  - view_mode:          {}".format(view_mode))
        print("  - examples:           {}".format(examples))
        print("  - debug:              {}".format(debug))

    # Show examples?
    if examples:
        print_examples()
        exit()

    # Settings
    settings = Settings() \
        .set_debug_level(debug) \
        .set_image_mode(image_mode) \
        .set_view_mode(view_mode) \
        .set_source_dir(source_dir) \
        .set_target_dir(target_dir) \
        .set_source_file_format(source_file_format) \
        .set_target_file_format(target_file_format) \
        .set_geometry(geometry) \
        .set_pages(pages)

    # Print settings
    settings.print_settings()

    # Hack to silently import Kivy's noisy logger:
    # The logger prints all kind of messages before the log level can be set
    # and seems to ignore its config file log level settings as well
    # (Kivy's config is at ~/.kivy/config.ini)
    if not debug in ['trace', 'debug', 'info']:

        # Silence stderr
        orig_stderr = sys.stderr
        sys.stderr = open(os.devnull, "w")

        # Import Kivy's logger
        from kivy.logger import Logger, LOG_LEVELS

        # Set the log level
        Logger.setLevel(level=LOG_LEVELS.get(debug))

        # Restore stdout
        sys.stderr = orig_stderr

    # Start the GUI
    # For some reason BookBlockApp cannot be imported before
    # as it seems to interfere with click
    from newskylabs.tools.bookblock.gui.main import BookBlockApp
    app = BookBlockApp(settings)
    app.run()

    # done :)
    print("")
    print("Bye :)")
    print("")
    exit()
예제 #15
0
파일: __init__.py 프로젝트: geojeff/kivy
            Activate a module (use "list" to get a list of available modules).
        -r, --rotation
            Rotate the window's contents (0, 90, 180, 270).
        -s, --save
            Save current Kivy configuration.
        --size=640x480
            Size of window geometry.
        --dpi=96
            Manually overload the Window DPI (for testing only.)
    """
    print(kivy_usage.__doc__ % (basename(sys.argv[0])))


# Start !
if "vim" in globals():
    Logger.setLevel(level=LOG_LEVELS.get("critical"))
else:
    Logger.setLevel(level=LOG_LEVELS.get("info"))
    Logger.info("Kivy v%s" % (__version__))

#: Global settings options for kivy
kivy_options = {
    "window": ("egl_rpi", "pygame", "sdl", "x11"),
    "text": ("pil", "pygame", "sdlttf"),
    "video": ("ffmpeg", "gstreamer", "pyglet", "null"),
    "audio": ("pygame", "gstreamer", "sdl"),
    "image": ("tex", "imageio", "dds", "gif", "pil", "pygame"),
    "camera": ("opencv", "gstreamer", "videocapture"),
    "spelling": ("enchant", "osxappkit"),
    "clipboard": ("pygame", "dummy"),
}
예제 #16
0
    def init_logger(self):

        # Store log messages until logger is configured
        log_messages = []

        # Init log level from ~/.bookblock or the defaults
        config = self.config
        log_dir    = config.get('logger', 'log_dir')
        log_name   = config.get('logger', 'log_name')
        log_level  = config.get('logger', 'log_level')
        log_enable = config.getint('logger', 'log_enable')
        #| log_maxfiles = config.getint('logger', 'log_maxfiles')

        # Ensure that log directory exists
        log_dir_path = PosixPath(log_dir).expanduser()
        print("log_dir_path:", log_dir_path)
        if not Path(log_dir_path).exists():
            log_messages.append("Creating log directory: {}".format(log_dir))
            log_dir_path.mkdir(parents=True, exist_ok=True)

        # Substitute the log file name format patterns with actual values
        # %y -> year, %m -> month, %d -> day, %_ -> next log file number
        log_file = log_name.replace('%_', '@@NUMBER@@')
        log_file = strftime(log_file)
        log_file = '{}/{}'.format(str(log_dir_path), log_file)
        n = 0
        while True:
            log_file2 = log_file.replace('@@NUMBER@@', str(n))
            if not os.path.exists(log_file2):
                log_file = log_file2
                break
            n += 1
            if n > 10000:  # prevent maybe flooding ?
                raise Exception('Too many logfile, remove them')
            
        # Open log file
        # and substitue it for the kivy log file (~/kivy/logs/...
        FileHandler.filename = str(log_file)
        if FileHandler.fd is not None:
            FileHandler.fd.close()
        FileHandler.fd = open(log_file, 'w')
        log_messages.append('Logger: Record log in %s' % log_file)

        # Log level
        # Command line option --debug overwrites settings
        log_level_option = self._settings.get_debug_level()
        if log_level_option != None:
            log_level = log_level_option

        # Convert to logging debug level
        log_level_code = LOG_LEVELS.get(log_level.lower())

        # When log_level is not one of 
        # trace, debug, info, warning, error, critical, 
        # None is returned.
        if log_level_code == None:
            log_levels = ['trace', 'debug', 'info', 'warning', 'error', 'critical']
            print("ERROR Undefined log level: {}\n".format(log_level) +
                  "Defined are only the following: {}.".format(', '.join(log_levels)),
                  file=sys.stderr)
            exit(-1)

        # Set log level
        Logger.setLevel(log_level_code)

        # En- / Disable logger
        Logger.logfile_activated = bool(log_enable)

        # TODO Purge old logs
        # See site-packages/kivy/logger.py, class FileHandler, method purge_logs() 
        # for an example of how to purge old logs.

        # Log stored log messages
        for msg in log_messages:
            Logger.info(msg)
            
        # Log some general information about Python, Kivy etc.
        
        # Kivys default logging level is info
        # In order to suppress the initial INFO messages printed when kivy is loaded
        # until the log level for `bookblock' is set
        # I set the level to WARNING by in file ~/.kivy/config.ini
        # > [kivy]
        # > #log_level = info
        # > log_level = warning
        # Some of the suppressed information is printed now
        # when the bookblock log level is lower or equal to INFO

        Logger.info('Kivy: v%s' % kivy.__version__)
        Logger.info('Kivy: Installed at "{}"'.format(kivy.__file__))
        Logger.info('Python: v{}'.format(sys.version))
        Logger.info('Python: Interpreter at "{}"'.format(sys.executable))
        Logger.info('Bookblock: Installed at "{}"'.format(dirname(dirname(__file__))))
        Logger.info('Bookblock: To avoid the Kivy startup INFO messages '
                    'change the kivy log level to WARNING '
                    'in ~/.kivy/config.ini')
        Logger.info('Bookblock: To avoid further messages from Bookblock '
                    'adapt the Bookblock log level in '
                    'in ~/.bookblock')
        Logger.info('Bookblock: For more debug information '
                    'change the kivy log level in ~/.kivy/config.ini '
                    'and the Bookblock log level in ~/.bookblock/config.ini '
                    'to TRACE, DEBUG, or INFO.')