1
0
mirror of https://github.com/craigerl/aprsd.git synced 2025-09-05 14:47:53 -04:00

Added new config to disable logging to console

This patch adds a new config setting to the logging
section that allows the user to disable logging to stdout.
This is useful for terminal UI apps :)
This commit is contained in:
Hemna 2025-02-26 17:41:40 -05:00
parent a3cda9f37d
commit 0fa5b07d4b
4 changed files with 67 additions and 55 deletions

View File

@ -13,35 +13,35 @@ from aprsd.utils import trace
CONF = cfg.CONF CONF = cfg.CONF
home = str(Path.home()) home = str(Path.home())
DEFAULT_CONFIG_DIR = f"{home}/.config/aprsd/" DEFAULT_CONFIG_DIR = f'{home}/.config/aprsd/'
DEFAULT_SAVE_FILE = f"{home}/.config/aprsd/aprsd.p" DEFAULT_SAVE_FILE = f'{home}/.config/aprsd/aprsd.p'
DEFAULT_CONFIG_FILE = f"{home}/.config/aprsd/aprsd.conf" DEFAULT_CONFIG_FILE = f'{home}/.config/aprsd/aprsd.conf'
F = t.TypeVar("F", bound=t.Callable[..., t.Any]) F = t.TypeVar('F', bound=t.Callable[..., t.Any])
common_options = [ common_options = [
click.option( click.option(
"--loglevel", '--loglevel',
default="INFO", default='INFO',
show_default=True, show_default=True,
type=click.Choice( type=click.Choice(
["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"], ['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'],
case_sensitive=False, case_sensitive=False,
), ),
show_choices=True, show_choices=True,
help="The log level to use for aprsd.log", help='The log level to use for aprsd.log',
), ),
click.option( click.option(
"-c", '-c',
"--config", '--config',
"config_file", 'config_file',
show_default=True, show_default=True,
default=DEFAULT_CONFIG_FILE, default=DEFAULT_CONFIG_FILE,
help="The aprsd config file to use for options.", help='The aprsd config file to use for options.',
), ),
click.option( click.option(
"--quiet", '--quiet',
is_flag=True, is_flag=True,
default=False, default=False,
help="Don't log to stdout", help="Don't log to stdout",
@ -59,7 +59,7 @@ class AliasedGroup(click.Group):
""" """
def decorator(f): def decorator(f):
aliases = kwargs.pop("aliases", []) aliases = kwargs.pop('aliases', [])
cmd = click.decorators.command(*args, **kwargs)(f) cmd = click.decorators.command(*args, **kwargs)(f)
self.add_command(cmd) self.add_command(cmd)
for alias in aliases: for alias in aliases:
@ -77,7 +77,7 @@ class AliasedGroup(click.Group):
""" """
def decorator(f): def decorator(f):
aliases = kwargs.pop("aliases", []) aliases = kwargs.pop('aliases', [])
cmd = click.decorators.group(*args, **kwargs)(f) cmd = click.decorators.group(*args, **kwargs)(f)
self.add_command(cmd) self.add_command(cmd)
for alias in aliases: for alias in aliases:
@ -101,36 +101,37 @@ def process_standard_options(f: F) -> F:
ctx = args[0] ctx = args[0]
ctx.ensure_object(dict) ctx.ensure_object(dict)
config_file_found = True config_file_found = True
if kwargs["config_file"]: if kwargs['config_file']:
default_config_files = [kwargs["config_file"]] default_config_files = [kwargs['config_file']]
else: else:
default_config_files = None default_config_files = None
try: try:
CONF( CONF(
[], [],
project="aprsd", project='aprsd',
version=aprsd.__version__, version=aprsd.__version__,
default_config_files=default_config_files, default_config_files=default_config_files,
) )
except cfg.ConfigFilesNotFoundError: except cfg.ConfigFilesNotFoundError:
config_file_found = False config_file_found = False
ctx.obj["loglevel"] = kwargs["loglevel"] ctx.obj['loglevel'] = kwargs['loglevel']
# ctx.obj["config_file"] = kwargs["config_file"] # ctx.obj["config_file"] = kwargs["config_file"]
ctx.obj["quiet"] = kwargs["quiet"] ctx.obj['quiet'] = kwargs['quiet']
log.setup_logging( log.setup_logging(
ctx.obj["loglevel"], ctx.obj['loglevel'],
ctx.obj["quiet"], ctx.obj['quiet'],
) )
if CONF.trace_enabled: if CONF.trace_enabled:
trace.setup_tracing(["method", "api"]) trace.setup_tracing(['method', 'api'])
if not config_file_found: if not config_file_found:
LOG = logging.getLogger("APRSD") # noqa: N806 LOG = logging.getLogger('APRSD') # noqa: N806
LOG.error("No config file found!! run 'aprsd sample-config'") LOG.error("No config file found!! run 'aprsd sample-config'")
del kwargs["loglevel"] del kwargs['loglevel']
del kwargs["config_file"] del kwargs['config_file']
del kwargs["quiet"] del kwargs['quiet']
return f(*args, **kwargs) return f(*args, **kwargs)
return update_wrapper(t.cast(F, new_func), f) return update_wrapper(t.cast(F, new_func), f)
@ -142,17 +143,17 @@ def process_standard_options_no_config(f: F) -> F:
def new_func(*args, **kwargs): def new_func(*args, **kwargs):
ctx = args[0] ctx = args[0]
ctx.ensure_object(dict) ctx.ensure_object(dict)
ctx.obj["loglevel"] = kwargs["loglevel"] ctx.obj['loglevel'] = kwargs['loglevel']
ctx.obj["config_file"] = kwargs["config_file"] ctx.obj['config_file'] = kwargs['config_file']
ctx.obj["quiet"] = kwargs["quiet"] ctx.obj['quiet'] = kwargs['quiet']
log.setup_logging( log.setup_logging(
ctx.obj["loglevel"], ctx.obj['loglevel'],
ctx.obj["quiet"], ctx.obj['quiet'],
) )
del kwargs["loglevel"] del kwargs['loglevel']
del kwargs["config_file"] del kwargs['config_file']
del kwargs["quiet"] del kwargs['quiet']
return f(*args, **kwargs) return f(*args, **kwargs)
return update_wrapper(t.cast(F, new_func), f) return update_wrapper(t.cast(F, new_func), f)

View File

@ -9,7 +9,7 @@ from aprsd.packets import core
from aprsd.utils import keepalive_collector from aprsd.utils import keepalive_collector
CONF = cfg.CONF CONF = cfg.CONF
LOG = logging.getLogger("APRSD") LOG = logging.getLogger('APRSD')
class APRSClient: class APRSClient:
@ -20,8 +20,8 @@ class APRSClient:
connected = False connected = False
login_status = { login_status = {
"success": False, 'success': False,
"message": None, 'message': None,
} }
filter = None filter = None
lock = threading.Lock() lock = threading.Lock()
@ -59,17 +59,20 @@ class APRSClient:
@property @property
def login_success(self): def login_success(self):
return self.login_status.get("success", False) return self.login_status.get('success', False)
@property @property
def login_failure(self): def login_failure(self):
return self.login_status["message"] return self.login_status['message']
def set_filter(self, filter): def set_filter(self, filter):
self.filter = filter self.filter = filter
if self._client: if self._client:
self._client.set_filter(filter) self._client.set_filter(filter)
def get_filter(self):
return self.filter
@property @property
def client(self): def client(self):
if not self._client: if not self._client:
@ -80,16 +83,16 @@ class APRSClient:
try: try:
self._client = self.setup_connection() self._client = self.setup_connection()
if self.filter: if self.filter:
LOG.info("Creating APRS client filter") LOG.info('Creating APRS client filter')
self._client.set_filter(self.filter) self._client.set_filter(self.filter)
except Exception as e: except Exception as e:
LOG.error(f"Failed to create APRS client: {e}") LOG.error(f'Failed to create APRS client: {e}')
self._client = None self._client = None
raise raise
def stop(self): def stop(self):
if self._client: if self._client:
LOG.info("Stopping client connection.") LOG.info('Stopping client connection.')
self._client.stop() self._client.stop()
def send(self, packet: core.Packet) -> None: def send(self, packet: core.Packet) -> None:
@ -103,16 +106,16 @@ class APRSClient:
@wrapt.synchronized(lock) @wrapt.synchronized(lock)
def reset(self) -> None: def reset(self) -> None:
"""Call this to force a rebuild/reconnect.""" """Call this to force a rebuild/reconnect."""
LOG.info("Resetting client connection.") LOG.info('Resetting client connection.')
if self._client: if self._client:
self._client.close() self._client.close()
del self._client del self._client
self._create_client() self._create_client()
else: else:
LOG.warning("Client not initialized, nothing to reset.") LOG.warning('Client not initialized, nothing to reset.')
# Recreate the client # Recreate the client
LOG.info(f"Creating new client {self.client}") LOG.info(f'Creating new client {self.client}')
@abc.abstractmethod @abc.abstractmethod
def setup_connection(self): def setup_connection(self):

View File

@ -54,6 +54,11 @@ logging_opts = [
default=True, default=True,
help='Enable ANSI color codes in logging', help='Enable ANSI color codes in logging',
), ),
cfg.BoolOpt(
'enable_console_stdout',
default=True,
help='Enable logging to the console/stdout.',
),
] ]

View File

@ -84,15 +84,18 @@ def setup_logging(loglevel=None, quiet=False):
logging.getLogger(name).handlers = [] logging.getLogger(name).handlers = []
logging.getLogger(name).propagate = name not in disable_list logging.getLogger(name).propagate = name not in disable_list
handlers = [ handlers = []
{ if CONF.logging.enable_console_stdout:
'sink': sys.stdout, handlers.append(
'serialize': False, {
'format': CONF.logging.logformat, 'sink': sys.stdout,
'colorize': CONF.logging.enable_color, 'serialize': False,
'level': log_level, 'format': CONF.logging.logformat,
}, 'colorize': CONF.logging.enable_color,
] 'level': log_level,
},
)
if CONF.logging.logfile: if CONF.logging.logfile:
handlers.append( handlers.append(
{ {