Skip to content

Instantly share code, notes, and snippets.

@dbnicholson
Created March 6, 2023 17:19
Show Gist options
  • Save dbnicholson/542df62c28a59315ad0b25f0c567b720 to your computer and use it in GitHub Desktop.
Save dbnicholson/542df62c28a59315ad0b25f0c567b720 to your computer and use it in GitHub Desktop.
from android.config import ACTIVITY_CLASS_NAME, SERVICE_CLASS_NAME
from jnius import autoclass
import logging
import os
logger = logging.getLogger('main') # __name__)
Log = autoclass('android.util.Log')
class AndroidHandler(logging.Handler):
LEVEL_MAP = {
logging.DEBUG: Log.DEBUG,
logging.INFO: Log.INFO,
logging.WARNING: Log.WARN,
logging.ERROR: Log.ERROR,
logging.CRITICAL: Log.ASSERT,
}
def __init__(self, tag=None):
super().__init__()
if not tag:
tag = self._get_package_name()
self.tag = tag
def emit(self, record):
try:
msg = self.format(record)
priority = self.LEVEL_MAP.get(record.levelno, Log.VERBOSE)
# tag = f'{self.tag}.{record.name}'
Log.println(priority, self.tag, msg)
except:
self.handleError(record)
@staticmethod
def _get_package_name():
if 'PYTHON_SERVICE_ARGUMENT' in os.environ:
context = autoclass(SERVICE_CLASS_NAME).mService
else:
context = autoclass(ACTIVITY_CLASS_NAME).mActivity
return context.getPackageName()
handler = AndroidHandler() # 'org.example.Simple')
logging.basicConfig(level=logging.DEBUG, handlers=[handler],
format='%(name)s:%(message)s')
print('print statement')
logger.debug('debug statement')
logger.info('info statement')
logger.warning('warning statement')
logger.error('error statement')
logger.critical('critical statement')
try:
raise Exception('some failure')
except:
logger.exception('A failure occurred')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment